如何在大尺寸位图上进行图像处理而不会崩溃

时间:2014-09-17 13:39:56

标签: android bitmap out-of-memory

我想加载一个大尺寸(大约10 MB)的图像,并让用户添加一些效果(如灰度等)。因此,我使用inSampleSize加载位图以向用户显示预览:

public Bitmap load(Context context, int[] holderDimention, String image_url) throws Exception {
    BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
    bitmapOptions.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(image_url, bitmapOptions);

    int inSampleSize = 1;

    final int outWidth = bitmapOptions.outWidth;
    final int outHeight = bitmapOptions.outHeight;

    final int holderWidth = holderDimention[0];
    final int holderHeight = holderDimention[1];

    // Calculation inSampleSize
    if (outHeight > holderHeight || outWidth > holderWidth) {
        final int halfWidth = outWidth / 2;
        final int halfHeight = outHeight / 2;

        while ((halfHeight / inSampleSize) > holderHeight && (halfWidth / inSampleSize) > holderWidth) {
            inSampleSize *= 2;
        }
    }

    bitmapOptions.inSampleSize = inSampleSize;

    // Decoding bitmap
    bitmapOptions.inJustDecodeBounds = false;
    return BitmapFactory.decodeFile(image_url, bitmapOptions);
}

最后,在后台我想在没有下采样的情况下对原始图像应用效果(这是必要的)。所以我在AsyncTask的子类中使用了以下代码:

public Bitmap load(Context context, String image_url) throws IOException {
    return BitmapFactory.decodeFile(image_url);
}

但是我得到了一个内存不足的例外。我怎么能处理这个问题?

1 个答案:

答案 0 :(得分:2)

你需要部分地做。仅加载部分图像,处理,保存部分。查看BitmapRegionDecoder

相关问题:Crop image without loading into memory