Android loaded image memory overflow problem solution

  • 2020-06-23 01:54:16
  • OfStack

1. In the process of Android software development, image processing is often encountered. Android API provides BitmapFactory.Options class to solve the problem of large images running out of memory when converting images to Bitmap due to their different sizes.

2. Due to Android's limited memory for images, large images loaded with a few megabytes will run out of memory. Bitmap will load all the pixels of the image (that is, the length x width) into memory. If the image resolution is too large, it will directly cause memory OOM. Only when BitmapFactory loads the image, it will use BitmapFactory.Options to configure related parameters to reduce the loaded pixels.

3. Details of BitmapFactory.Options parameters:

(1).Options.inPreferredConfig value to reduce memory consumption.
For example: the default value ARGB_8888 is changed to RGB_565, saving one and a half memory.
(2). Set Options. inSampleSize scale to compress large pictures.
(3). Setting ES31en. inPurgeable and inInputShareable: enable the system to retrieve the memory in time.
A: inPurgeable: When set to True, it means that the system can be recycled when it is out of memory. When set to False, it means that it cannot be recycled.
B: inInputShareable: This parameter is meaningless when inPurgeable is false.

(4) Use decodeStream instead of other methods.

decodeResource setImageResource, setImageBitmap method, etc

4. Code:


public static Bitmap getBitmapFromFile(File file, int width, int height) {

    BitmapFactory.Options opts = null;
    if (null != file && file.exists()) {

      if (width > 0 && height > 0) {
        opts = new BitmapFactory.Options();
        //  It just returns the width and height of the image, not the height 1 a Bitmap object 
        opts.inJustDecodeBounds = true;
        //  Information is not saved in bitmap Inside, it's stored in options inside 
        BitmapFactory.decodeFile(file.getPath(), opts);
        //  Calculate image scaling 
        final int minSideLength = Math.min(width, height);
        //  The thumbnail size is a fraction of the size of the original image 1 . Do it according to business requirements. 
        opts.inSampleSize = computeSampleSize(opts, minSideLength,
            width * height);
        //  Re-read the picture and note that the options.inJustDecodeBounds Set back false
        opts.inJustDecodeBounds = false;
        //  Sets whether to copy deeply, and inPurgeable Use a combination of 
        opts.inInputShareable = true;
        //  Set to True Can be returned when the system is out of memory   Ok, set to False Can't be recycled. 
        opts.inPurgeable = true;
      }
      try {
        return BitmapFactory.decodeFile(file.getPath(), opts);
      } catch (OutOfMemoryError e) {
        e.printStackTrace();
      }
    }
    return null;
  }

Related articles: