从SdCard android解码文件以避免由于大位图或setImageURI导致的内存不足错误

Mah*_*esh 2 resources android image sd-card

从sdcard或资源中选择大图像文件时避免内存不足错误.我该如何解决这个问题?

Mah*_*esh 12

要在位图中从SD卡中选择文件或使用setImageURI到sdcard时避免错误,请使用以下方法:

public static Bitmap decodeScaledBitmapFromSdCard(String filePath,
        int reqWidth, int reqHeight) {

    // First decode with inJustDecodeBounds=true to check dimensions
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(filePath, options);

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

    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;
    return BitmapFactory.decodeFile(filePath, options);
}

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;
}
Run Code Online (Sandbox Code Playgroud)

  • 有关更多信息,请使用此文档:http://developer.android.com/training/displaying-bitmaps/load-bitmap.html (2认同)