bitmap压缩图片:
/**
*
* @param data 网络请求返回的图片字节数组
* @param maxWidth ImageView最大宽度
* @param maxHeight ImageView最大高度
* @param config 解码Bitmap时使用的配置属性:
* Bitmap.Config.ARGB_8888,一个像素占4个字节
* Bitmap.Config.ARGB_4444,一个像素占2个字节
* Bitmap.Config.ALPHA_8, 一个像素占1个字节
* Bitmap.Config.RGB_565, 一个像素占2个字节
* @return 二次采样后的bitmap图片
*/
public Bitmap createBitmapThumb(byte[] data, int maxWidth,
int maxHeight, Config config) {
Options options = new Options();
//第一次采样,目的获取inSampleSize的比例
options.inJustDecodeBounds = true;
//当将inJustDecodeBounds之为true时,调用decodeByteArray方法时不会
//分配内存空间,只会讲图片的宽高填充到Options中的outWidth和outHeight
BitmapFactory.decodeByteArray(data, 0, data.length, options);
//获取图片的实际宽高
int oldWidth = options.outWidth;
int oldHeight = options.outHeight;
if(maxHeight == 0 && maxWidth == 0) {
options.inSampleSize = 1;
} else if(maxHeight == 0 && maxWidth != 0) {
options.inSampleSize = oldWidth / maxWidth;
} else if(maxHeight != 0 && maxWidth == 0) {
options.inSampleSize = oldHeight / maxHeight;
} else {
int ratioWidth = oldWidth / maxWidth;
int ratioHeight = oldHeight / maxHeight;
options.inSampleSize = ratioWidth > ratioHeight ? ratioWidth : ratioHeight;
}
//第二次采样
options.inJustDecodeBounds = false;
options.inPreferredConfig = config;
Bitmap bm = BitmapFactory.decodeByteArray(data, 0, data.length, options);
return bm;
}