Bitmap的优化
一、概念
ALPHA_8: 表示 8位Alpha位图, 即A=8,一个像素点占用1个字节,它没有颜色,只有透明度
ARGB_4444:表示16位ARGB 位图,即A=4,R=4,G=4,B=4,一个像素点占4+4+4+4=16位,2个字节
ARGB_8888:表示32位ARGB 位图,即A=8,R=8,G=8,B=8,一个像素点占8+8+8+8=32位,4个字节
RGB_565: 表示16位RGB 位图, 即R=5,G=6,B=5,它没有透明度,一个像素点占5+6+5=16位,2个字节
二、方法:
decodeFile、decodeResource、decodeStream。
decodeFile和decodeResource->decodeResourceStream最终都是调用decodeStream
三、优化
(1).质量压缩
public static Bitmap compressImage(Bitmap bitmap) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);//质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中
int options = 100; //循环判断如果压缩后图片是否大于50kb,大于继续压
while (baos.toByteArray().length / 1024 > 50) {
//清空baos
baos.reset();
bitmap.compress(Bitmap.CompressFormat.JPEG, options, baos);
options -= 10;//每次都减少10
}
//把压缩后的数据baos存放到ByteArrayInputStream中
ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
//把ByteArrayInputStream数据生成图片
Bitmap newBitmap = BitmapFactory.decodeStream(isBm, null, null);
return newBitmap;
}
(2).尺寸压缩:inJustDecodeBounds预判断Bitmap的大小及使用inSampleSize进行压缩
public static Bitmap decodeSampledBitmapFromResourse(Resources resources, int resId, int reqWidth, int reqHeight) {
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(resources, resId, options);
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
options.inJustDecodeBounds = true;
return BitmapFactory.decodeResource(resources, resId, options);
}
public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
int outWidth = options.outWidth;
int outHeight = options.outHeight;
int sampleSize = 1;
if (outWidth > reqWidth || outHeight > reqHeight) {
int halfWidth = outWidth / 2;
int halfHeight = outHeight / 2;
while ((halfWidth / sampleSize) > reqWidth && (halfHeight / sampleSize > reqHeight)) {
sampleSize *= 2;
}
}
return sampleSize;
}