Bitmaps 的重要有效方法 之一

我们都知道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));


猜你喜欢

转载自bdql.iteye.com/blog/1857023