参考了网上的大侠们的压缩方法,但觉得不尽人意,所以自己写了一个压缩方法,如下:
本人亲测,压缩一张400多k, 2592*1552的图片,
将k设为50(因为要取得缩略图),压缩之后图片7k,大小为81*48
有少许偏差,因为在计算过程中double与int的转换及int的运算都会出现四舍五入的情况
/**
* 压缩图片
* @param s--图片所在路径
* @param k--缩放后图片(目标图片)的宽或高
* savePath--缩放后图片的存储路径
* @return
*/
public Bitmap scalePicture(String s,String savePath, int k){
Bitmap bitmap=null;
try{
BitmapFactory.Options options =new BitmapFactory.Options();
options.inJustDecodeBounds =true;
// 获取这个图片的宽和高
bitmap =BitmapFactory.decodeFile(s, options); //此时返回bm为空
int be = 0;
be= (int)Math.sqrt((options.outHeight/k)*(options.outWidth/k));
if (be <= 1)
be = 1;
options.inJustDecodeBounds =false;
options.inSampleSize = be;
//重新读入图片,注意这次要把options.inJustDecodeBounds 设为 false
bitmap=BitmapFactory.decodeFile(s,options);
System.out.println("be----------------->"+be);
//保存入sdCard
File file2= new File(savePath);
try {
FileOutputStream out = new FileOutputStream(file2);
if(bitmap.compress(Bitmap.CompressFormat.PNG, 100, out)){
out.flush();
out.close();
}
} catch (Exception e) {
// TODO: handle exception
return null;
}
}catch(Exception e){
e.printStackTrace();
return null;
}
return bitmap;
}