Android Memory optimized image compression and caching

Source: Internet
Author: User

Due to the limitations of cell phone memory and the cost of network traffic now, when loading images, we must compress and cache the images.

The image caching mechanism generally has 2 kinds, soft reference and memory cache technology.

1. Compress the picture: Compress the picture to neither blur nor stretch the picture.

Picture operation, the most commonly used is bitmapfactory, now see how to compress the picture.

Bitmapfactory.options options= new Bitmapfactory.options ();

Options.injustdecodebounds = true;//If you set this parameter to Ture, you do not allocate memory space to the picture, but you can get properties such as the size of the picture

2. Soft reference: As long as there is enough memory, always remain exclusive until the memory is tight and there is no strong reference when the object is recycled.

Mainly used SoftReference, use as follows:

Private map<string,softreference<bitmap> ImageMap = new Hasmap<string,softreference<bitmap>> () ;

Here the key is mainly the image of the address, can be the network address, or the SD card can be the image address.

3. Memory caching technology: In Android, there is a LRUCache class, which is specifically used to do the image cache processing. When the cached image reaches a predetermined threshold, the images with the least number of recent usage are recycled. So first to set the image memory size, and then set the LRUCache inside the key value pair, url and picture, rewrite sizeof, return the number of pictures.

4. After Android 2.3, GCC will be more inclined to recover soft or weak reference objects, but also can not be cached locally, cache to local can easily cause oom, so it is best to lrucache cache, set threshold value, more than the recovery.

Android Memory optimized image compression and caching

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.