Bitmap面试最简单的回答

本文深入探讨Bitmap的四种类型:ALPHA_8、ARGB_4444、ARGB_8888和RGB_565,以及Bitmap的解码方法如decodeFile、decodeResource和decodeStream。此外,还介绍了两种优化Bitmap的方法:质量压缩和尺寸压缩,通过调整压缩选项和使用inSampleSize参数来有效减小Bitmap的大小。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;
	}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值