Android--memory optimization of images

Source: Internet
Author: User

Reprint Please specify source: http://blog.csdn.net/l1028386804/article/details/46972817
1. Manipulate the picture itself

Try not to use Setimagebitmap, Setimageresource, Bitmapfactory.decoderesource to set a large picture, because these methods after the decode, and finally all through the Java layer CreateBitmap to complete, you need to consume a lot of other memory. So. Instead, first pass the Bitmapfactory.decodestream method. Create a bitmap and set it to the source of ImageView. Decodestream's biggest secret lies in its direct call to Jni>>nativedecodeasset () to complete the decode. No longer need to use Java layer createbitmap. This saves the Java layer of space.

Assuming that the Config parameter is added to the read, it is more efficient to reduce the loaded memory and thus more effectively prevent the throwing of memory exceptions. Other than that. Decodestream directly take the picture to read the bytecode, not according to the various resolutions of the machine to actively adapt themselves. After using the Decodestream. The corresponding picture resources need to be configured in hdpi and mdpi,ldpi, otherwise the same size (number of pixels) will be the same on different resolution machines. The size shown is not correct.

InputStream is = This.getresources (). Openrawresource (R.drawable.pic); Bitmapfactory.options Options = new Bitmapfactory.options (); options.injustdecodebounds = False;options.insamplesize = 2; Bitmap BTP =bitmapfactory.decodestream (is,null,options);
The above code reads a thumbnail image named Pic under drawable. The length and width are 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 becomes worse. The greater the value of the insamplesize. The quality of the picture is worse. Because each handset manufacturer scales the picture the algorithm is different. Scaling pictures on different phones may be of different quality.

2. Call the Recycle () method of the picture

if (!bmp.isrecycle ()) {   bmp.recycle ()/    /Reclaim the memory of the picture   System.GC ()      //Remind the system to recycle it in time}

Such a method is not actually 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 Java heap is used enough. And the picture takes place 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. Just a picture object called recycle () is in an "obsolete" state, which causes a program error when invoked. So there is no guarantee that the picture object will never be called again. It is not recommended to use this method.

Pay special attention to the use of Setimagebitmap (Bitmap

img) method to assign a picture object to the control. May be called by the System class library. Cause a program error. 3. Read a picture of a local resource in the most memory-saving way

/** * Read the picture of a local resource in the most memory-saving way */public static Bitmap Readbitmap (context context, int resId) {     bitmapfactory.options opt = new Bitmapfactory.options ();     Opt.inpreferredconfig = Bitmap.Config.RGB_565;     Opt.inpurgeable = true;     Opt.ininputshareable = true;     Get the resource picture     InputStream is = Context.getresources (). Openrawresource (resId);     Return Bitmapfactory.decodestream (is,null,opt);  }
There are four color modes for loading images into Android. Each is: alpha_8: Each pixel occupies 1byte of memory, argb_4444: Each pixel occupies 2byte memory, argb_8888: Each pixel occupies 4byte memory, rgb_565: Each pixel occupies 2byte memory. The default color mode for Android is argb_8888. This color mode is the most delicate color, showing the highest quality. But the same. Memory is also the largest.

The above code reads the picture resource in rgb_565 (or argb_4444) mode. Memory loss Although not as obvious as the first method, for most images, there is no difference between the argb_8888 pattern. A color bar may appear when you're reading a picture with a gradient effect.

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:

Although you use the Matrix object to enlarge the picture. Will inevitably consume a lot of other memory. But sometimes it has to be done.

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 image color mode using the following method.

Matrix matrix = new Matrix (); float newwidth = n;       Picture enlarged width of float newheight =;      Image enlarged Length Matrix.postscale (Newwidth/img.getwidth (), Newheight/img.getheight ()); Bitmap IMG1 = Bitmap.createbitmap (img, 0, 0, img.getwidth (), Img.getheight (), Matrix, True);//get enlarged picture Img2 = Img1.copy (bitm Ap. config.argb_4444, false);                           Get the picture of argb_4444 color mode img = 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 the memory used by every pixel in the image.

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's memory takeover mechanism. Recycle something is certainly effective in some degree. But it always feels inappropriate to accept the principle of Java memory takeover.

Android--memory optimization of images

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.