Bitmap 压缩

在Android开发中,处理图像时经常需要对Bitmap进行压缩,以减少内存使用和提高应用性能。以下是一些常见的Bitmap压缩方法:
1. 质量压缩
质量压缩是通过改变图像的编码质量来减少文件大小,但不会改变图像的宽度和高度。这通常用于减少图像文件的大小,以便于网络传输或存储。
Bitmap bitmap = ...; // 获取Bitmap对象
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream);
byte[] bytes = outputStream.toByteArray();
其中,Bitmap.CompressFormat可以是JPEG、PNG或WEBP。quality参数是一个0到100的整数,表示压缩质量,0表示最低质量,100表示最高质量。


2. 尺寸压缩
尺寸压缩是通过改变图像的宽度和高度来减少内存占用。这通常用于在显示图像之前将其缩小到目标视图的大小。
Bitmap bitmap = ...; // 获取Bitmap对象
int targetWidth = ...; // 目标宽度
int targetHeight = ...; // 目标高度
Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap, targetWidth, targetHeight, false);


3. 采样率压缩(inSampleSize
采样率压缩是通过减少图像的分辨率来减少内存占用。这在加载大图像到内存时非常有用。
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true; // 设置为true,只读取Bitmap的尺寸信息,不加载到内存
BitmapFactory.decodeResource(getResources(), R.id.myimage, options);
int sampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
options.inSampleSize = sampleSize; // 设置采样率
options.inJustDecodeBounds = false; // 设置为false,加载Bitmap到内存
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.id.myimage, options);
calculateInSampleSize方法通常是这样实现的:
public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
    // 原始图像的宽度和高度
    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 1;
    if (height > reqHeight || width > reqWidth) {
        final int halfHeight = height / 2;
        final int halfWidth = width / 2;
        // 计算最大的inSampleSize值,该值是2的幂并且保持高度和宽度大于请求的高度和宽度
        while ((halfHeight / inSampleSize) >= reqHeight && (halfWidth / inSampleSize) >= reqWidth) {
            inSampleSize *= 2;
        }
    }
    return inSampleSize;
}


注意事项
质量压缩不会改变Bitmap对象的内存占用,它只影响存储时的文件大小。
尺寸压缩和采样率压缩会减少Bitmap对象的内存占用。
在进行采样率压缩时,inSampleSize必须是2的幂,否则可能会导致图像失真。
压缩图像时,要注意保持图像的可见质量,避免过度压缩导致图像模糊不清。
通过合理地使用这些压缩方法,可以有效地管理应用的内存使用,提高性能和用户体验。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值