Bitmaps 的重要有效方法 之一

本文介绍了一种使用BitmapFactory.Options类的方法来优化大尺寸位图的加载和显示过程,通过两次解码操作,先测量尺寸再进行压缩,从而避免内存溢出错误。示例代码展示了如何将任意大小的位图加载到指定大小的缩略图。

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

我们都知道BitmapFactory类提供几种解码方法 (decodeByteArray()、 decodeFile()、 decodeResource()等) 从各种来源中创建一个Bitmap。选择最合适的解码方法基于您的图像数据源。这些方法尝试为构造位图分配内存,因此可以很容易有OutOfMemory异常的结果。

java.lang.OutofMemoryError: bitmap size exceeds VM budget.这种蛋疼的问题是因为CCD对每个android应用有内存限制16M,现在放宽了,但是如果把十几兆的图片直接显示出来那肯定是要挂滴。
怎么办咧?压缩小了的显示吧。

BitmapFactory.Options是关键

具体的做法是用两次解码!
第一次解码,其目的是测量尺寸,如果oom了也没关系
然后计算压缩比例
第二次解码,变小了
public static int calculateInSampleSize(
            BitmapFactory.Options options, int reqWidth, int reqHeight) {
    // Raw height and width of image
    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 1;

    if (height > reqHeight || width > reqWidth) {

        // Calculate ratios of height and width to requested height and width
        final int heightRatio = Math.round((float) height / (float) reqHeight);
        final int widthRatio = Math.round((float) width / (float) reqWidth);

        // Choose the smallest ratio as inSampleSize value, this will guarantee
        // a final image with both dimensions larger than or equal to the
        // requested height and width.
        inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
    }

    return inSampleSize;
}

注:inSampleSize值是2 的幂。
inJustDecodeBounds设置为true

public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId,
        int reqWidth, int reqHeight) {
    Bitmap bm = null;
    // First decode with inJustDecodeBounds=true to check dimensions
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    try {
        BitmapFactory.decodeResource(res, resId, options);
    } catch (OutOfMemoryError e) {
        System.gc();
    }

    // Calculate inSampleSize
    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;
    try {
        bm = BitmapFactory.decodeResource(res, resId, options);
    } catch (OutOfMemoryError e) {
         System.gc();
    }
    return bm;
}

这种方法容易地将任意大小的位图加载到显示 100 x 100 像素的缩略图,如下面的代码示例所示:
mImageView.setImageBitmap(
    decodeSampledBitmapFromResource(getResources(), R.id.myimage, 100, 100));


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值