Android image performance optimization,

Source: Internet
Author: User

Android image performance optimization,

This chapter describes how to optimize image processing in android development. Including big Image loading, Image compression, Image cache processing, and the open-source Image Processing Framework Universal-Image-Loader.

1. Insufficient memory caused by images

When loading a high-resolution image in an android Application, the Out of memory (OOM) is very likely to occur, which is caused by memory overflow, the size of heap memory used by each application is usually fixed, some are 16 MB, and some may be larger. So why does an image overflow when such a large memory is loaded? The reason is that android uses bitmap to put images into memory when loading images. the space occupied by the image in memory is calculated as the resolution * Memory occupied by each pixel.

  • 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

If the resolution of an image is 1024*768 and ARGB_8888 is used, the occupied space is 1024*768*4 = 3 MB. This image occupies 3 MB of memory, for such images, if only the same is loaded, the memory will be able to cope with it, if the resolution is higher. For example, for a 3648*2736 photo, the memory usage is 3648*2736*4 = 33 MB. This image occupies 33 MB space and will definitely cause memory overflow. What should we do?

  • Reduce the image size (resolution) when the image is loaded into the memory ).
  • Use memory-saving encoding, such as ARGB_4444.
  • Cache can also be used to load a large number of images.
2. BitmapFactory. options class Introduction

BitmapFactory. Options is an internal class of BitmapFactory. It is mainly used to set and store information about BitmapFactory loading images. The following are the attributes required in Options:

  • Options. inJustDecodeBounds: if it is set to true, the pixel array of the image is not loaded into the memory, and only some additional data (slice size) is loaded into Options.
  • Options. outHeight: The image height.
  • Options. outWidth: The image width.
  • Options. inSampleSize: If this parameter is set, the image is loaded Based on the sampling rate and cannot be set to a value smaller than 1. For example, if it is set to 4, the resolution width and height will be 1/4 of the original, and the overall memory will be 1/16 of the original.
  • Options. inDither: Set to false to avoid image jitter.
  • Options. inPreferredConfig: Set to null so that the decoder can be decoded in the optimal way.

For large image processing, it is usually displayed on mobile devices through compression. The processing code for a specified image is as follows:

1 // The large image is compressed into a wide, PX high image display 2 BitmapFactory. options options = new Options (); 3 options. inJustDecodeBounds = true; 4 BitmapFactory. decodeResource (rs, R. drawable. a2, options); 5 options. inPreferredConfig = Bitmap. config. ARGB_4444; 6 options. inSampleSize = calculateInSampleSize (options, 200,200); // obtain the compression factor 7 options. inJustDecodeBounds = false; 8 Bitmap bitmap = BitmapFactory. decodeResource (rs, R. drawable. a2, options); 9 iv. setImageBitmap (bitmap); // image binding

For example, if the ratio of a large image is 1 and the compression parameter is set to 2 or 4, the processing effect is shown in:

3. Introduction to Universal-Image-Loader

Universal-Image-Loader is an open-source UI component program designed to provide a reusable instrument for asynchronous Image loading, caching, and display.

The entire library is divided into five modules: ImageLoaderEngine, Cache and ImageDownloader, ImageDecoder, BitmapDisplayer, and BitmapProcessor. The Cache is divided into MemoryCache and DiskCache. To put it simply, ImageLoader receives the task of loading and displaying images and submits it to ImageLoaderEngine. ImageLoaderEngine distributes the task to a specific thread pool for execution. The task obtains images through Cache and ImageDownloader, it may be processed by BitmapProcessor and ImageDecoder in the middle, and finally converted to Bitmap and handed over to BitmapDisplayer for display in ImageAware.

(1) ImageLoader features
  • Multi-threaded image loading possibilities wide tuning for ImageLoader configuration (thread pool size, http options, memory and CD cache, display image, and others)
  • Possible image cache memory and/or Device File System (or SD card)
  • It can be listened to during loading
  • You can customize the call separation options for each displayed Image
  • Widget support
  • Support for Android 1.5 and later versions
  • Supports download progress monitoring
  • You can pause image loading in View scrolling. You can pause image loading in View scrolling through the PauseOnScrollListener interface.
  • Multiple Memory Cache algorithms are implemented by default. Cache algorithms can be configured for these image caches, but ImageLoader implements many caching algorithms by default, for example, the maximum Size is deleted first, the minimum Size is used first, the minimum Size is recently used, the first time is deleted first, and the longest time is deleted first.
  • Supports rule definition of local cache file names

Briefly describe the structure of this project: each image loading and display task runs in an independent thread, unless the image is cached in the memory, this will be immediately displayed. If the desired image is saved locally, an independent thread queue is enabled. If there is no correct picture in the cache, the task thread will get it from the thread pool. Therefore, there is no obvious obstacle to quickly display the cached picture.

Flowchart:

(2) ImageLoader Parameters

MageLoaderConfiguration is the configuration parameter of ImageLoader of the image loader. The Builder mode is used. The createDefault () method is used to create a default ImageLoaderConfiguration. The default setting parameters are as follows:

 1 File cacheDir = StorageUtils.getCacheDirectory(context); 2 ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context) 3   .memoryCacheExtraOptions(480, 800) // default = device screen dimensions 4   .diskCacheExtraOptions(480, 800, CompressFormat.JPEG, 75, null) 5   .taskExecutor(...) 6   .taskExecutorForCachedImages(...) 7   .threadPoolSize(3) // default 8   .threadPriority(Thread.NORM_PRIORITY - 1) // default 9   .tasksProcessingOrder(QueueProcessingType.FIFO) // default10   .denyCacheImageMultipleSizesInMemory()11   .memoryCache(new LruMemoryCache(2 * 1024 * 1024))12   .memoryCacheSize(2 * 1024 * 1024)13   .memoryCacheSizePercentage(13) // default14   .diskCache(new UnlimitedDiscCache(cacheDir)) // default15   .diskCacheSize(50 * 1024 * 1024)16   .diskCacheFileCount(100)17   .diskCacheFileNameGenerator(new HashCodeFileNameGenerator()) // default18   .imageDownloader(new BaseImageDownloader(context)) // default19   .imageDecoder(new BaseImageDecoder()) // default20   .defaultDisplayImageOptions(DisplayImageOptions.createSimple()) // default21   .writeDebugLogs()22   .build();
(3) configure the Android Manifest File

During use, the image is obtained through the network and has cache settings. Therefore, you need to add the following two permissions.

1  <uses-permission android:name="android.permission.INTERNET" />  2 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 

(4) ImageLoader operation

Set the directory of the cached file to imageloader/Cache.

File cacheDir = StorageUtils. getOwnCacheDirectory (getApplicationContext (), "imageloader/Cache ");

. DiscCache (UnlimitedDiscCache (cacheDir ))

ImageLoader is generally configured in Application. You can use displayImagesoptions to set other parameters. The reference code is as follows:

1 // configure Config 2 ImageLoaderConfiguration config = new ImageLoaderConfiguration 3 in Application. builder (context) 4. memoryCacheExtraOptions (480,800) // max width, max height, that is, the maximum length and width of each stored cache file 5. discCacheExtraOptions (480,800, CompressFormat. JPEG, 75, null) // Can slow ImageLoader, use it carefully (Better don't use it)/set the detailed information of the cache. it is best not to set this 6. threadPoolSize (3) // Number of threads loaded in the thread pool 7. threadPriority (Thread. NORM_PRIORITY-2) 8. denyCacheImageMultipleSizesInMemory () 9. memoryCache (new UsingFreqLimitedMemoryCache (2*1024*1024) // You can pass your own memory cache implementation/You can achieve 10 through your memory cache. memoryCacheSize (2*1024*1024) 11. discCacheSize (50*1024*1024) 12. discCacheFileNameGenerator (new Md5FileNameGenerator () // encrypt the URI name when it is saved with MD5 13. tasksProcessingOrder (QueueProcessingType. LIFO) 14. discCacheFileCount (100) // Number of cached files 15. discCache (new UnlimitedDiscCache (cacheDir) // customize the cache path 16. defaultDisplayImageOptions (DisplayImageOptions. createSimple () 17. imageDownloader (new BaseImageDownloader (context, 5*1000, 30*1000) // connectTimeout (5 s), readTimeout (30 s) Timeout time 18. writeDebugLogs () // Remove for release app 19. build (); // start to build 20 // Initialize ImageLoader with configuration. 21 22 // After Congfig is configured, Global Initialization is as follows: 23 ImageLoader. getInstance (). init (config); // global initialization of this configuration 24 25 // define the image display settings 26 DisplayImageOptions; 27 options = new DisplayImageOptions when the image is displayed. builder () 28. showImageOnLoading (R. drawable. ic_launcher) // sets the image displayed during the download process. 29. showImageForEmptyUri (R. drawable. ic_launcher) // sets the image 30 when the image Uri is null or incorrect. showImageOnFail (R. drawable. ic_launcher) // sets the picture 31 when an error occurs during image loading/decoding. cacheInMemory (true) // sets whether the downloaded image is cached in memory. cacheOnDisc (true) // sets whether the downloaded image is cached in the SD card. considerExifParams (true) // determines whether to consider the JPEG image EXIF parameter (rotation, flip) 34. imageScaleType (ImageScaleType. EXACTLY_STRETCHED) // sets how the image is encoded. 35. bitmapConfig (Bitmap. config. RGB_565) // set the image decoding type // 36. decodingOptions (android. graphics. bitmapFactory. options decodingOptions) // set the image decoding configuration 37 //. delayBeforeLoading (int delayInMillis) // int delayInMillis sets the delay time before downloading for you 38 // sets the bitmap to 39 //. preProcessor (BitmapProcessor preProcessor) 40. resetViewBeforeLoading (true) // sets whether to reset the image before downloading, and resets the value by 41. displayer (new RoundedBitmapDisplayer (20) // determines whether to set it to a rounded corner and how many radians are 42. displayer (new FadeInBitmapDisplayer (100) // determines whether the image is loaded and the animation time is gradually 43. build (); // build complete

Loadimage:

1 // use the loadImage () method of ImageLoader to load the network image 2 final ImageView mImageView = (ImageView) findViewById (R. id. image); 3 String imageUrl = ""; // define the address obtained from the image network. 4 // specify the image size. 5 ImageSize mImageSize = new ImageSize (100,100 ); 6 // display image configuration 7 DisplayImageOptions options = new DisplayImageOptions. builder () 8. cacheInMemory (true) 9. cacheOnDisk (true) 10. bitmapConfig (Bitmap. config. RGB_565) 11. build (); 12 // define the image to load 13 ImageLoader. getInstance (). loadImage (imageUrl, mImageSize, options, new SimpleImageLoadingListener () {14 @ Override15 public void onLoadingStarted (String imageUri, View) {16 17} 18 @ Override19 public void onLoadingFailed (String imageUri, view view, 20 FailReason failReason) {21 22} 23 24 @ Override25 public void onLoadingComplete (String imageUri, View view, Bitmap loadedImage) {26 // post-processing 27 mImageView after successful loading. setImageBitmap (loadedImage); 28 29} 30 31 @ Override32 public void onLoadingCancelled (String imageUri, View view) {33 34} 35 });

Displayimage:

1 final ImageView mImageView = (ImageView) findViewById (R. id. image); 2 String imageUrl = ""; // obtain the image address through the network. 3 // display the image configuration. 4 DisplayImageOptions options = new DisplayImageOptions. builder () 5. showImageOnLoading (R. drawable. ic_stub) 6. showImageOnFail (R. drawable. ic_error) 7. cacheInMemory (true) 8. cacheOnDisk (true) 9. bitmapConfig (Bitmap. config. RGB_565) 10. build (); 11 12 imageLoader. displayImage (imageUrl, imageView, options, new ImageLoadingListener () {13 @ Override 14 public void onLoadingStarted () {15 // run 16 when loading starts} 17 @ Override 18 public void onLoadingFailed (FailReason failReason) {19 // execute 20 when loading fails} 21 @ Override 22 public void onLoadingComplete (Bitmap loadedImage) {23 // run 24 when loading successfully} 25 @ Override 26 public void onLoadingCancelled () {27 // run 28 when loading is canceled}, new ImageLoadingProgressListener () {29 @ Override 30 public void onProgressUpdate (String imageUri, View view, int current, int total) {31 // update progress information of ProgressBar here 32} 33 });

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.