Detailed explanation of Android bitmap and memory optimization of bitmap

Detailed explanation of Android bitmap and memory optimization of bitmap

1、 Bitmap:

Bitmap is one of the most important classes of image processing in Android system. It can be used to obtain the image file information, cut, rotate and zoom the image, and save the image file in a specified format.

Common methods:

2、 Bitmapfactory factory class:

Option parameter class:

Factory method:

Bitmap.Config inPreferredConfig :

Enumerating variables (the higher the bit number of bitmap, the more color information it can store, the more realistic the image, and the more memory it occupies)

The memory occupied by a picture (bitmap) in Android is mainly related to the following factors: picture length, picture width, and the number of bytes occupied per pixel. Memory occupied by a picture (bitmap) = picture length * picture width * bytes occupied per pixel.

3、 Bitmap loading method

The loading methods of bitmap include resource loading, local (sdcard) loading, network loading, etc.

1. Read from local (sdcard) file

Mode 1

Mode 2 (higher efficiency than mode 1)

2. Read the file from the input stream (network load)

3. Resource loading

Res resource loading method:

This method consumes considerable memory. It is recommended to use decodestream instead of decoderesource, which can be in the following form:

The pictures loaded by bitmapfactory.decoderesource may be scaled. At present, the scaling is done in the Java layer, which is inefficient and consumes the memory of the Java layer. Therefore, if you use this interface heavily to load pictures, it is easy to cause oom errors

Bitmapfactory.decodestream does not scale the loaded pictures, which occupies less memory and is more efficient.

These two interfaces are useful. If performance requirements are high, decodestream should be used; If you don't have high performance requirements and need the self-adaptive image scaling function of Android, you can use decoderesource.

2. Assets resource loading method:

4. Read pictures from binary data

4、 Convert between bitmap | drawable | InputStream | byte []

Convert drawable to bitmap

Drawable: drawable drawable = getresources(). Getdrawable (r.drawable. Ic_launcher);

2. Convert bitmap to drawable

3. Convert bitmap to byte []

4. Convert byte [] to bitmap

5. Converting InputStream to bitmap

6. Convert InputStream to byte []

5、 Simple operation of bitmap

1. Save bitmap as a local file:

2. Picture compression:

3. Picture zoom:

4. Obtain the rotation angle of the picture:

5. Set the rotation angle of the picture

6. Obtain bitmap through image ID:

7. Obtain drawable bitmap through assert:

8. Obtain bitmap through sdcard

9. View to bitmap

10. Convert control to bitmap

11. Zoom in and out

12. Method of obtaining fillet image

13. Cut the bitmap

6、 Detailed explanation of bitmap memory optimization

In Android applications, the most memory consuming is image resources. Moreover, in the Android system, when reading the bitmap, the stack size of the pictures allocated to the virtual machine is only 8m. If it exceeds, an OUTOFMEMORY exception will appear. Therefore, image memory optimization is an important content in Android application development.

1. Recover bitmap memory in time

Bitmap class has a method recycle (), which means recycle according to the method name. There is a doubt here. The Android system has its own garbage collection mechanism, which can recycle unused memory space from time to time, including bitmap space. Then why do you need this method?

The construction methods of bitmap class are private, so developers cannot directly create a bitmap object, but can only instantiate a bitmap through various static methods of bitmapfactory class. Looking carefully at the source code of bitmapfactory, we can see that the generation of bitmap objects is finally realized through JNI call. Therefore, after loading bitmap into memory, it contains two memory areas. In short, one part is Java and the other part is C. This bitmap object is partially allocated by Java and will be automatically recycled when not in use. However, the virtual machine cannot directly recycle the memory area available for C. This can only be released by calling the underlying function. Therefore, you need to call the recycle () method to free the memory of Part C. It can also be seen from the source code of the bitmap class that the JNI method is indeed called in the recycle () method.

Is there a memory leak if you don't call recycle()? Not really. Each Android application runs in an independent process with independent memory. If the whole process is killed by the application itself or the system, the memory will be released, including part C of the memory. Android process management is very complex. In short, the processes of the Android system are divided into several levels. The system will kill some low priority processes in case of insufficient memory to provide sufficient memory space for other processes. In the actual project development process, some developers will use process. Killprocess (process. Mypid()) to kill their processes when exiting the program, but some applications will only close all activities by calling the activity. Finish() method.

Sample code snippet for releasing bitmap:

As can be seen from the above code, the bitmap. Recycle () method is used to recycle the memory occupied by the bitmap, then empty the bitmap, and finally call the system garbage collector with system. GC () to recycle. You can notify the garbage collector to recycle as soon as possible. It should be noted here that calling system. GC () does not guarantee the immediate start of the recycling process, but only to speed up the arrival of recycling.

We know how to call the recycle () method for recycling. When is it appropriate to release bitmap memory? Generally speaking, if the code no longer needs to use bitmap objects, it can be released. After the memory is released, the bitmap object can no longer be used. If it is used again, an exception will be thrown. So be sure to release it when it is no longer in use. For example, if you use bitmap in an activity, you can recycle it in the onstop () or ondestroy () methods of the activity.

2. Catch exception

In order to avoid crashing after an OUTOFMEMORY exception occurs when the application allocates bitmap memory, special attention should be paid to the code of instantiating the bitmap part. In general, OUTOFMEMORY exceptions must be caught in the code instantiating bitmap.

The OUTOFMEMORY exception that may occur during the initialization of the bitmap object is captured here. If an OUTOFMEMORY exception occurs, the application will not crash, but will get a default bitmap.

Note: many developers will habitually catch exceptions directly in the code. However, for outofmemoryerror, this is not captured. Because outofmemoryerror is an error, not an exception. Just a reminder here to avoid writing wrong code and not capturing outofmemoryerror.

3. Cache common bitmap objects

Sometimes, you may need to use the same picture multiple times in an activity. For example, an activity will display a list of user avatars. If the user does not set a avatar, a default avatar will be displayed, which is located in the resource file of the application itself. If there is a scenario similar to the above, you can cache the same bitmap. If you do not cache, although you see the same picture file, the bitmap instantiated using the method of bitmapfactory class is a different bitmap object. Caching can avoid creating multiple bitmap objects and waste of memory. Cache technology is often used in Android application development. The cache mentioned here has two levels: hard disk cache and memory cache. For example, in the process of developing network applications, you can save some data obtained from the network to the SD card and read it directly from the SD card next time instead of from the network, so as to save network traffic. This method is hard disk cache. For another example, applications often use the same object, which can also be cached in memory and read directly from memory when necessary. This method is memory caching.

4. Compressed picture

If the picture pixel is too large, OUTOFMEMORY exception is bound to occur when more than 8m memory space is required during the instantiation of bitmap using the method of bitmapfactory class. What should we do at this time? If this is the case, you can reduce the size of the picture to reduce the use of memory in the process of loading the picture and avoid exceptions.

Use bitmapfactory.options to set insamplesize to zoom out the picture. The property value insamplesize indicates that the thumbnail size is a fraction of the original picture size. That is, if this value is 2, the width and height of the extracted thumbnail are 1 / 2 of the original picture, and the size of the picture is 1 / 4 of the original size.

If you know that the pixels of the picture are too large, you can reduce it. So how do you know that the picture is too big?

Using bitmapfactory.options to set injustdecodebounds to true, and then using methods such as decodefile() will not really allocate space, that is, the decoded bitmap is null, but the width and height of the original picture can be calculated, that is, options.outwidth and options.outheight. Through these two values, you can know whether the picture is too large.

In the actual project, you can use the above code to obtain the real width and height of the picture, and then judge whether you need to run and shrink. If you do not need to zoom out, set the value of insamplesize to 1. If you need to zoom out, dynamically calculate and set the value of insamplesize to zoom out the picture. It should be noted that the next time you instantiate a bitmap object using methods such as bitmapfactory's decodefile(), don't forget to set opts.injustdecodebound back to false. Otherwise, the obtained bitmap object is still null.

Note: if the source of the image of the program is the resources in the package or the image on your own server, and the size of the image can be adjusted by the developer, generally speaking, you only need to pay attention to the use of the image not to be too large, pay attention to the quality of the code, and recycle the bitmap object in time to avoid OUTOFMEMORY exceptions. If the picture of the program comes from the outside, you should pay special attention to OUTOFMEMORY at this time. One is that if the loaded image is large, it needs to be reduced first; The other is to catch exceptions to avoid program crash.

Thank you for reading, hope to help you, thank you for your support to this site!

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>