Asynchronous Full parsing of Android load Bitmap

Source: Internet
Author: User

Asynchronous Full parsing of Android load Bitmap
Asynchronous Full parsing of Android load Bitmap

In this article, we have analyzed some Android strategies for big image processing-Android asynchronously loading full resolution big image processing stamp me

So in this article, we will perform a more detailed analysis on the image-Bitmap to grasp the bit by bit of Bitmap.

 

The introduction of Bitmap is known as the number one killer of Android apps, especially versions earlier than 3.0. It is simply an emperor-like existence and cannot be touched or broken. Although the later versions of Android have also made a series of Optimizations to Bitmap management, it is still very difficult to handle. In Android asynchronous loading, the network access is slow and slow, that is, images. Text is flushed, but images are always unavailable, this made many people who read & ** & % &) * & images very depressed. But there is no way. You all like to watch pictures, so you still have to figure out images.
Bitmap exists in previous versions, that is, in the Android2.3 era. The object reference of Bitmap is stored separately from its real pixel data, the object reference of Bitmap is stored in the heap of the Dalvik Virtual Machine heap memory, but the pixel data is stored in the system memory. We need to call the recycle () method to release the memory of the pixel information, however, if you use Bitmap again after the release, the program will have FC. After the evolution to Android3.0, the object reference and pixel data of Bitmap are stored in the heap of the Dalvik Virtual Machine heap. In this way, the recovery of Bitmap memory resources is completely handed over to GC, so this can avoid many OOM problems. Moreover, in the 2.3 era, GC is single-threaded, once recycled, the interface is stuck, and after 3.0, GC is changed to concurrent execution, and the working thread is not blocked. Although the system has done a lot of behind-the-scenes work for us, OOM, due to various Bitmap code problems, will also let the program FC, so when we use Bitmap, you must pay attention to it. For example, to avoid Memory leakage and memory overflow, you can also add android: largeHeap = "true" in the application of the mainifest file to let the system take special care of you, use more memory space. However, this is not a solution after all. It can only be used as a life-saving skill. Remember and remember!
Android asynchronous loading of the full resolution big image processing this is no longer necessary, please refer to the stamp me
Introducing Cache during asynchronous loading of full parsing in Android is a very important method to optimize the Bitmap storage policy. You don't need to talk about this anymore. Please refer to the first timestamp me, but here are some points that need to be mentioned again. Whether it is LruCache or DiskLruCache, setting the cache size is not generalized, it is necessary to make a comprehensive judgment based on the Bitmap usage frequency and Bitmap pixel size equivalent in the project.
SoftReference and BitmapFactory. options. the inBitmap parameter has introduced BitmapFactory since Android3.0. options. inBitmap. If this field is set, the Bitmap referenced by this field will be reused during decoding to avoid Memory reallocation. However, when using this attribute, there are some conditions:
1. the reused Bitmap and the Bitmap to be decoded must be of the same size and be in JPEG or PNG format.
2. The BitmapFactory. Options. inPreferredConfig field setting is invalid because it will be overwritten by the configuration of the reused Bitmap.
3. Use Bitmap returned by the decoding method because reuse may fail. 4. Bitmap must be variable, that is, the inmutable setting must be true. Remember, the loaded source images cannot be modified.
In addition, in Android 3.0 (API Level 11) and later versions, when Bitmap is squeezed out from LruCache, we can store the soft reference of this Bitmap as the inBitmap for future decoding. In this way, you can find detailed examples on the developer website, so I will not install them ~~ Essential tool for developers-http://developer.android.com/training/displaying-bitmaps/manage-memory.html
Here we will further explain the Demo on the official website. When we use the cache to optimize Bitmap, we use LruCache, and LruCache has such a method-entryRemoved. According to the document, this method is called when the LruCache container is full and objects in it need to be eliminated to free up space. However, note that only objects are eliminated from the LruCache container, but it does not mean that the object's memory will be immediately reclaimed by the Dalvik virtual machine. At this time, we can wrap Bitmap Using SoftReference in this method and use a pre-prepared HashSet container to store these bitmaps to be recycled. When the preceding conditions are met, the system will check whether there is a reusable Bitmap in the memory when decoder the image, avoid the system performance degradation caused by frequent image loading from the SD card. After all, the SD card is much slower than the memory speed. The rest of us will use the Demo on the official website and it will be OK. Now, the package is over.
In PS, we usually use decodeStream and decodeFile to parse the obtained stream information, for example:
URL url = new URL(urlString);          HttpURLConnection conn = (HttpURLConnection) url.openConnection();          is = new BufferedInputStream(conn.getInputStream());          bitmap = BitmapFactory.decodeStream(is);  

In fact, the system also provides us with a more efficient method-decodeFileDescriptor. Why is it so efficient? It is actually a historical reason. We all know that C is a little faster than Java, so, decodeFileDescriptor is slightly faster than decodeStream because decodeFileDescriptor uses the underlying library for parsing in the source code, for example:
FileInputStream is = = new FileInputStream(path);bmp = BitmapFactory.decodeFileDescriptor(is.getFD(), null, opts);
Therefore, this method can be faster than decodeFile when DiskLruCache is called. Here we also provide a complete call code:
Public static OutputStream decodeBitmap (String path) {BitmapFactory. options opts = new BitmapFactory. options (); opts. inJustDecodeBounds = true; // if this parameter is set to true, the bitmap width and height BitmapFactory are obtained without memory occupation. decodeFile (path, opts); opts. inSampleSize = computeSampleSize (opts,-1, 1024*800); opts. inJustDecodeBounds = false; // you must set it back to false, because we set it to true opts before. inPurgeable = true; opts. ininputretriable = true; opts. inDither = false; opts. inPurgeable = true; opts. inTempStorage = new byte [16*1024]; FileInputStream is = null; Bitmap bmp = null; InputStream ins = null; ByteArrayOutputStream baos = null; try {is = new FileInputStream (path ); bmp = BitmapFactory. decodeFileDescriptor (is. getFD (), null, opts); double scale = getScaling (opts. outWidth * opts. outHeight, 1024*600); Bitmap BMP 2 = Bitmap. createScaledBitmap (bmp, (int) (opts. outWidth * scale), (int) (opts. outHeight * scale), true); bmp. recycle (); baos = new ByteArrayOutputStream (); BMP 2.compress (Bitmap. compressFormat. JPEG, 100, baos); BMP 2.recycle (); return baos;} catch (FileNotFoundException e) {e. printStackTrace ();} catch (IOException e) {e. printStackTrace ();} finally {try {is. close (); ins. close (); baos. close ();} catch (IOException e) {e. printStackTrace ();} System. gc ();} return baos;} private static double getScaling (int src, int des) {/*** target size unknown original size sqrt open, returns the percentage of width and height */double scale = Math. sqrt (double) des/(double) src); return scale ;}

Please forgive me for the Bitmap Secondary Sampling technology. In fact, the Secondary Sampling Technology sounds awesome, in fact, we use the method we use in "big image processing" to stamp me, that is, inSampleSize. When we load a large image, we can quickly load a thumbnail with a very low quality, after the source image is downloaded, load it again.
Bitmap image compression size is compressed by the inSampleSize method. In fact, we have implemented Bitmap compression. However, this compression is based on the size. As we have discussed earlier, I will not talk about it here. The following describes a quality-based compression method. Of course, this method is also the API-compress method, so there is no need for too many algorithms.
Private Bitmap compressImage (Bitmap bitmap) {ByteArrayOutputStream baos = new ByteArrayOutputStream (); // quality compression method. Here, 100 indicates that the compressed data is not compressed and stored in bitmap of baos. compress (Bitmap. compressFormat. JPEG, 100, baos); int options = 100; // cyclically determine whether the size of the image after compression is greater than kb. toByteArray (). length/1024> 100) {// reset baos to clear baosbaos. reset (); // here, compress options % and store the compressed data to bitmap in baos. compress (Bitmap. compressFormat. JPEG, options, baos); // reduce each time by 10 options-= 10;} // Save the compressed data baos to ByteArrayInputStream isBm = new ByteArrayInputStream (baos. toByteArray (); // generate ByteArrayInputStream data to the image Bitmap bitmap = BitmapFactory. decodeStream (isBm, null, null); return bitmap ;}

 




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.