Android--bitmap Performance Optimization

Source: Internet
Author: User

Do the project today, found that need to display a large picture, after processing, there are 561Kb

When loaded, crash---OOM.

ShortMsg:java.lang.OutOfMemoryError

LongMsg:java.lang.OutOfMemoryError:bitmap size exceeds VM budget

StackTrace:java.lang.OutOfMemoryError:bitmap size exceeds VM budget
At Android.graphics.Bitmap.nativeCreate (Native Method)
At Android.graphics.Bitmap.createBitmap (bitmap.java:477)
At Android.graphics.Bitmap.createBitmap (bitmap.java:444)
At Android.graphics.Bitmap.createScaledBitmap (bitmap.java:349)
At Android.graphics.BitmapFactory.finishDecode (bitmapfactory.java:512)
At Android.graphics.BitmapFactory.decodeStream (bitmapfactory.java:487)
At Android.graphics.BitmapFactory.decodeResourceStream (bitmapfactory.java:336)

The code is as follows:

This line'll leads to OOM

      detailview=(ImageView) Findviewbyid (R.id.detailview);      DetailView. Setbackgroundresource (r.drawable.more_info);

Change to this:

      DetailView. Setimageresource // It will also be oom .

Later found the solution:

    /*** Read pictures of local resources in the most memory-saving way *@paramContext *@paramResId *@return     */     Public StaticBitmap Readbitmap (Context context,intresId) {bitmapfactory.options opt=Newbitmapfactory.options (); Opt.inpreferredconfig=Bitmap.Config.RGB_565; Opt.inpurgeable=true; Opt.ininputshareable=true; //get a picture of a resourceInputStream is =context.getresources (). Openrawresource (ResId); returnBitmapfactory.decodestream (IS,NULL, opt); }

After getting bitmap, DetailView again. Setimagebitmap (Pdfimage); It's OK!

That's why it can lead to Oom:

Originally when using like

Imageview.setbackgroundresource,

Imageview.setimageresource,

Bitmapfactory.decoderesource such a way to set a large picture of the time

After completing the decode, these functions are ultimately done through the Java layer's CreateBitmap , which consumes more memory.

So

1, switch to first through bitmapfactory. Decodestream method to create a bitmap

2, and then set it to ImageView source,Decodestream The biggest secret is that it directly call jni>>Nativedecodeasset() to complete the decode, There is no need to use Java layer CreateBitmap, which saves the Java layer space.

If the config parameter of the picture is added to the read, it can be used to reduce the loaded memory effectively, thereby effectively blocking the throw out of the "Memories" exception.

In addition, special attention is required:

Decodestream is directly read the image data byte code , not according to the machine's various resolutions to automatically adapt, after using the Decodestream , you need to configure the corresponding picture resources in hdpi and mdpi,ldpi. Otherwise the same size (number of pixels) is the same on different resolution machines, and the displayed size is wrong.


There are several ways to avoid oom problems when loading picture resources:
1, it is recommended to use Bitmapbefore Android 2.3.3. Recycle () method to release resources in a timely manner.

1, starting on Android 3.0

can be set the BitmapFactory.options.inBitmap value, obtained from the cache , achieves the purpose of reusing the bitmap. If set, the value of the Inpreferredconfig property is overwritten by the Bitmap of the property value that is reused.

2, by setting options. inpreferredconfig value to reduce memory consumption:
argb_8888:4 bytes per pixel.   Total 32 bits. It is the default value
Alpha_8: Only save transparency, total 8 bits, 1 bytes.
argb_4444: Total 16 bits, 2 bytes.
rgb_565: Total 16 bits, 2 bytes.
If you do not need transparency , you can change the default value argb_8888 to rgb_565, saving half the memory.
3, by setting the options.insamplesize to compress the large picture, you can set the Optionsfirst. Injustdecodebounds, get the peripheral data of bitmap, width and height , etc. The compression ratio is then calculated and compressed.
4, set options.inpurgeable and ininputshareable: Allow the system to recover memory in time.
1, inpurgeable:

(1) Set to True, the bitmap created with Bitmapfactory is used to store pixel memory space, can be reclaimed when the system is out of memory, and the system will call pixel again when the application needs to access the bitmapfactory of the bitmap again The Decode method regenerates the bitmap pixel array.
(2) When set to False, indicates that it cannot be recycled.

2, Ininputshareable: Set whether deep copy, and inpurgeable in combination with, inpurgeable false, this parameter is meaningless.
True:share a reference to the input data (InputStream, ARRAY,ETC)

False:a Deep Copy
5, use Decodestream instead of other decoderesource,setimageresource,setimagebitmap and other methods to load the picture.
Difference:
(1) Decodestream directly read the image byte code, call Nativedecodeasset/nativedecodestream to complete the decode. Save Dalvik memory by eliminating the need to use some extra processing of Java space. However, due to the direct reading of the bytecode, there is no processing, and therefore does not automatically adapt to the various resolutions of the machine, need to configure the corresponding picture resources in hdpi,mdpi and ldpi, otherwise the same size (number of pixels) on different resolution machines, the actual size of the display is incorrect.
Decoderesource will be after reading the image data, according to the machine's resolution, the image of the appropriate processing, resulting in a lot of dalvik memory consumption increased.

Decodestream Call procedure: Decodestream (inputstream,rect,options), Nativedecodeasset/nativedecodestream
Decoderesource call procedure: After Finishdecode, call the extra Java layer CreateBitmap method, consume more Dalvik memory.
Decoderesource (resource,resid,options), Decoderesourcestream (SET options indensity and Intargetdensity parameters) Decodestream () (decode after completion of the Finishdecode operation)
Finishdecode (), Bitmap.createscalebitmap (), Bitmap.createbitmap (based on indensity and intargetdensity calculation scale)

Use the combination of the above methods to avoid oom errors reasonably.

Android--bitmap Performance Optimization

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.