Solve the basic usage problems of Android and BitmapFactory

  • 2021-12-21 05:04:49
  • OfStack

Problem description

Error reporting using BitmapFactory. decodeFile to Bitmap: java.lang.RuntimeException: Canvas: trying to draw too large(120422400bytes) bitmap.

Solutions

Error cause: Image converted to Bitmap exceeds the maximum value MAX_BITMAP_SIZE


frameworks/base/graphics/java/android/graphics/RecordingCanvas.java

public static final int MAX_BITMAP_SIZE = 100 * 1024 * 1024; // 100 MB

/** @hide */
@Override
protected void throwIfCannotDraw(Bitmap bitmap) {
    super.throwIfCannotDraw(bitmap);
    int bitmapSize = bitmap.getByteCount();
    if (bitmapSize > MAX_BITMAP_SIZE) {
        throw new RuntimeException(
                "Canvas: trying to draw too large(" + bitmapSize + "bytes) bitmap.");
    }
}

Amend as follows


// Before modification 
Bitmap image = BitmapFactory.decodeFile(filePath);
imageView.setImageBitmap(image);

// After modification 
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.DisplayMetrics;

File file = new File(filePath);
if (file.exists() && file.length() > 0) {
    // Get the device screen size 
    DisplayMetrics dm = getResources().getDisplayMetrics();
    int screenWidth = dm.widthPixels;
    int screenHeight = dm.heightPixels;
    // Get the width and height of the picture 
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;	
    BitmapFactory.decodeFile(filePath, options);	
    float srcWidth = options.outWidth;	
    float srcHeight = options.outHeight;	
    // Calculate the scaling ratio 
    int inSampleSize = 1;	
    if (srcHeight > screenHeight || srcWidth > screenWidth) {	
        if (srcWidth > srcHeight) {	
            inSampleSize = Math.round(srcHeight / screenHeight);	
        } else {	
            inSampleSize = Math.round(srcWidth / screenWidth);	
        }	
    }	
    options.inJustDecodeBounds = false;	
    options.inSampleSize = inSampleSize;	
    
    Bitmap bitmap = BitmapFactory.decodeFile(filePath, options);	
    imageView.setImageBitmap(bitmap);
}

Related references:

Detailed Explanation of Bitmap for Android Image Cache
https://juejin.cn/post/6844903442939412493

BitmapFactory
https://developer.android.com/reference/android/graphics/BitmapFactory.html

BitmapFactory.options
BitmapFactory. Options class is a configuration parameter class used by BitmapFactory when decoding pictures, in which a series of public member variables are defined, and each member variable represents one configuration parameter.
https://blog.csdn.net/showdy/article/details/54378637


Related articles: