Memory-optimized methods for images in Android

Source: Internet
Author: User

Android in the image of the memory optimization method, the need for friends can refer to

1. Manipulate the picture itself

Try not to use Setimagebitmap, Setimageresource, Bitmapfactory.decoderesource to set up a large map, because these methods after the completion of decode, and ultimately through the Java layer CreateBitmap to complete, it consumes more memory. Therefore, instead of using the Bitmapfactory.decodestream method first to create a bitmap, and then set it to ImageView Source,decodestream the biggest secret is its direct call jni>> Nativedecodeasset () to complete the decode, eliminating the need to use the Java layer CreateBitmap, thus saving the Java layer of space. If the Config parameter is added at the time of reading, it can more effectively reduce the loaded memory, thus more effectively prevent throwing memory exception. In addition, Decodestream directly take the picture to read the bytecode, not according to the machine's various resolutions to automatically adapt, after using the Decodestream, you need to configure the corresponding image 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.

The code is as follows:

this new false = 2=bitmapfactory.decodestream (IS,  Null, Options);

The above code is read drawable under the name of the pic image thumbnail, length, width is only 1/2 of the original picture. The image size is reduced, and the memory used naturally becomes smaller. The disadvantage of this is that the picture quality is poor, the larger the value of the insamplesize, the picture quality is worse. Scaling pictures on different phones may be different depending on the algorithm used by each handset maker to scale pictures.

2. Call the Recycle () method of the picture

The code is as follows:

if (! bmp.isrecycle ()) {   bmp.recycle ()    // recover the memory of the picture   System.GC ()      // Reminder System timely recovery }

This approach is not really a way to actually reduce the image memory. The main purpose is to mark the image object so that the local data of the image object is easily recycled. The local data of a picture object occupies the largest amount of memory and is calculated separately from the memory in the Java portion of the program. So often the Java heap is enough to use, and the picture takes place in a outofmemoryerror situation. Calling this method when the picture is not in use can effectively reduce the peak value of local data in the image, thus reducing the probability of outofmemoryerror. However, a picture object called recycle () is in an "obsolete" state, which causes a program error when invoked. Therefore, it is not recommended to use this method if it is not guaranteed that the picture object will never be called again. Pay special attention to the use of Setimagebitmap (Bitmapimg) method is assigned to the control's picture object and may be called by the System class library, resulting in a program error.

3. Read a picture of a local resource in the most memory-saving way

The code is as follows:

/*** Read pictures of local resources in the most memory-saving way*/ 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); }

There are four color modes for loading images in Android: alpha_8:1byte per pixel, argb_4444:2byte memory per pixel, argb_8888:4byte memory per pixel, rgb_565: per pixel occupancy 2byte of memory. Android default color mode for argb_8888, this color mode color is the most delicate, showing the highest quality. But the same, the memory is also the largest. The above code reads the picture resource in rgb_565 (or argb_4444) mode. Memory reduction is not as obvious as the first method, but for most pictures, there is no difference between the argb_8888 pattern. However, when you read a picture with a gradient effect, a color bar may appear. In addition, it will affect the effect of the image processing.

4. How to change the color mode of a picture enlarged with the Matrix object:

While zooming in on a picture with a Matrix object will certainly consume more memory, but sometimes you have to. The enlarged image uses the argb_8888 color mode, even if the original picture is argb_4444 color mode, and there is no way to specify the color mode directly when zoomed in. You can change the picture color mode in the following ways.

The code is as follows:

Matrix Matrix =NewMatrix ();floatNewwidth = 200;//width of enlarged imagefloatNewheight = 300;//the length of the image after enlargementMatrix.postscale (Newwidth/img.getwidth (), newheight/img.getheight ()); Bitmap IMG1= Bitmap.createbitmap (img, 0, 0, img.getwidth (), Img.getheight (), Matrix,true);//Get enlarged pictureImg2 = Img1.copy (Bitmap.Config.ARGB_4444,false);//get a picture of argb_4444 color modeIMG =NULL; IMG1=NULL;

This creates an additional picture object IMG1 than the original image. But the system will actively accept the takeover img1, so the actual memory is still cut.

It boils down to reading pictures in thumbnail mode and cutting down on the memory used by each pixel in the picture most effectively. These two methods are effective, but also have their own shortcomings. The actual opening up or should be applied according to the scene as appropriate. The most benevolent way, or to avoid the generation of garbage objects. For example, in the application of the ListView, multiplexing Convertview and so on. If you apply asynctask to load a picture, set the referenced ImageView object to NULL in time. Because Asynctask is implemented with a thread pool, the objects referenced in this may have a very long life cycle, causing the GC to be unable to be acquitted. I still rely on Android memory accept takeover mechanism, recycle what is certainly the extent of effective, but always feel inappropriate Java memory accept takeover principle.

Memory-optimized methods for images in Android

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.