图片的压缩
相关知识点:http://blog.csdn.net/yezhouyong/article/details/50402022
http://blog.csdn.net/jdsjlzx/article/details/44228935
http://www.cnblogs.com/mmy0925/archive/2013/01/22/2870815.html (讲解decodeFile())
样板:
(这里所传的参数reqWidth和reqHeigt为我们获取的控件实际宽度,不知道获取的控件实际宽度看 点击打开链接)
BitmapFactory.Options options=new BitmapFactory.Options();
//获取得图片的宽高,并不把图片加载到内存中
options.inJustDecodeBounds=true;
BitmapFactory.decodeFile(path,options);
options.inSampleSize=caculateInSampleSize(options,width,height);
//把图片加载到内存中
options.inJustDecodeBounds=false;
//使用获取到的压缩比值再次解析图片
Bitmap bitmap=BitmapFactory.decodeFile(path,options);
return bitmap;
图片压缩分两大步:
1.我们去解析一个图片,如果太大,就会outOfMemory,所以我们拿到图片时,就不能先存放在内 存中。设置:
//获取得图片的宽高,并不把图片加载到内存中
options.inJustDecodeBounds=true;
2.然后我们设置压缩比(options.inSampleSize)
options.inSampleSize=caculateInSampleSize(options,width,height);
private int caculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
int width=options.outWidth;
int height=options.outHeight;
int inSampleSize=0;
if (width>reqWidth||height>reqHeight){
int widthRadio=Math.round(width*1.0f/reqWidth);
int heightRadio=Math.round(height*1.0f/reqHeight);
//inSampleSize如果去最大值Max就是将图片压缩到最小,如果取最小值Min就是让
//图片原比例压缩,但会比Max值压缩的图片更耗内存,这里我们为了节约内存用Max值
inSampleSize=Math.max(widthRadio,heightRadio);
}
return inSampleSize;
}