Android Memory Optimization-image Optimization

Source: Internet
Author: User

Operate the image itself. Try not to use setImageBitmap, setImageResource, BitmapFactory. decodeResource to set a large image, because these methods are completed through the createBitmap on the java layer after the decode is completed, requiring more memory consumption. Therefore, use BitmapFactory first. the decodeStream method creates a bitmap and sets it as the source of ImageView. The biggest secret of decodeStream is that it directly calls JNI> nativeDecodeAsset () to complete decode, you no longer need to use the createBitmap on the java layer, thus saving the java Layer Space. If the configuration parameter of the slice is added during reading, the loaded memory can be reduced more effectively to prevent memory exceptions from being thrown. In addition, decodeStream directly reads bytecode from images and does not automatically adapt to various machine resolutions. After decodeStream is used, it must be in hdpi and mdpi, configure the corresponding image resources in ldpi. Otherwise, the images are of the same size (number of pixels) on machines with different resolutions. The displayed size is incorrect.

Copy codeThe Code is as follows: InputStreamis = this. getResources (). openRawResource (R. drawable. pic1 );
BitmapFactory. Optionsoptions = newBitmapFactory. Options ();
Options. inJustDecodeBounds = false;
Options. inSampleSize = 10; // width, hight is set to the original 10-minute-one
Bitmapbtp = BitmapFactory. decodeStream (is, null, options );

Copy codeThe Code is as follows: if (! Bmp. isRecycle ()){
Bmp. recycle () // reclaim the memory occupied by the image
System. gc () // remind the system to recycle it in time
}

Copy codeThe Code is as follows :/**
* Read images of local resources in the most memory-saving manner
* @ Paramcontext
* @ ParamresId
* @ Return
*/
PublicstaticBitmapreadBitMap (Contextcontext, intresId ){
BitmapFactory. Optionsopt = newBitmapFactory. Options ();
Opt. inPreferredConfig = Bitmap. Config. RGB_565;
Opt. inPurgeable = true;
Opt. ininputtransferable = true;
// Obtain the resource Image
InputStreamis = context. getResources (). openRawResource (resId );
ReturnBitmapFactory. decodeStream (is, null, opt );
}

The value in option refers to the scaling ratio of the image. In the SDK, it is recommended that the value be 2. The larger the value, the image is unclear. The length and width are only 1/2 of the original image. The image size is reduced, and the memory occupied is naturally reduced. The disadvantage of this is that the image quality is deteriorated. The larger the value of inSampleSize, the worse the image quality. Because mobile phone manufacturers have different Image Scaling algorithms, the image quality on different mobile phones may be different. I have encountered a situation where the quality is acceptable after the moto mobile phone is scaled. Samsung mobile phones have the same scaling ratio, but the quality is much worse.

There are four types of Android::
ALPHA_8: each pixel occupies 1 byte of memory
ARGB_4444: each pixel occupies 2 bytes of memory
ARGB_8888: each pixel occupies 4 bytes of memory
RGB_565: each pixel occupies 2 bytes of memory
The default color mode for Android is ARGB_8888. This color mode features the most delicate colors and the highest display quality. However, the memory is also the largest.
The preceding code is used to read 1.png in ARGB_4444 mode. Although the memory reduction is not as obvious as the first method, most images cannot see any difference with the ARGB_8888 mode. However, when reading images with gradient effects, there may be color bars. In addition, it will affect the special effect processing of the image.
Optimize the heap memory allocation of the Dalvik virtual machine. For the Android platform, the DalvikJavaVM used by its hosting layer can be optimized from the current performance, for example, when developing large game or resource-consuming applications, we may consider Manual Interference with GC and use dalvik. system. the setTargetHeapUtilization method provided by the VMRuntime class can improve the processing efficiency of the program heap memory. Usage:Copy codeThe Code is as follows: privatefinalstaticfloatTARGET_HEAP_UTILIZATION = 0.75f;
VMRuntime. getRuntime (). setTargetHeapUtilization (TARGET_HEAP_UTILIZATION );

You can.
You can also define the heap memory size.Copy codeThe Code is as follows: privatefinalstaticintCWJ_HEAP_SIZE = 6*1024*1024; VMRuntime. getRuntime (). setMinimumHeapSize (CWJ_HEAP_SIZE); // set the minimum heap memory to 6 MB.

Call the recycle () method of the image:
This is not actually a way to actually reduce the image memory. The main purpose is to mark the image object to facilitate the collection of local data of the image object. The local data of the image object occupies the largest memory and is calculated separately from the Java memory of the program. Therefore, Javaheap is often enough for use, while OutOfMemoryError occurs in images. This method can be called when the image is not in use, effectively reducing the peak value of the local data of the image, thus reducing the probability of OutOfMemoryError. However, the image object that calls recycle () is in the "obsolete" state, which may cause a program error. Therefore, this method is not recommended when it cannot guarantee that the image object will never be called again. Note that image objects that have been allocated to the control using the setImageBitmap (Bitmapimg) method may be called by the system class library and cause program errors.

How to change the color mode of an image magnified by a Matrix object:
Although using a Matrix object to enlarge an image will consume more memory, sometimes you have to do the same. The enlarged image uses the ARGB_8888 color mode, even if the original image is in the ARGB_4444 color mode, and there is no way to directly specify the color mode when you zoom in. You can change the image color mode in the following ways.
The Code is as follows:Copy codeThe Code is as follows: Matrixmatrix = newMatrix ();
FloatnewWidth = 200; // The width of the enlarged image
FloatnewHeight = 300; // The enlarged image Length
Matrix. postScale (newWidth/img. getWidth (), newHeight/img. getHeight ());
Bitmapimg1 = Bitmap. createBitmap (img, img. getWidth (), img. getHeight (), matrix, true); // The enlarged image is obtained.
Img2 = img1.copy (Bitmap. Config. ARGB_4444, false); // obtain the image in the ARGB_4444 color mode.
Img = null;
Img1 = null;

Here an additional image object img1 is generated compared to the original image. However, the system automatically recycles img1, so the actual memory is reduced.

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.