in writing Android programs often use a lot of pictures, different pictures will always have different shapes, different sizes, but in most cases, these images will be larger than the size of our program. For example, the pictures in the system pictures are mostly taken from the mobile phone camera, the resolution of these images is much higher than the resolution of our phone screen. As you should know, we write applications that have a certain memory limit, and programs that consume too much memory are prone to OOM (OutOfMemory) exceptions. Picture optimization can give users a good experience, beautify the program interface and avoid the program appearing OOM. The following article tells us how much memory is available for each application by code, and of course we can detect app performance through third-party tools :http://www.ineice.com/
int maxmemory = (int) (Runtime.getruntime (). MaxMemory ()/1024);
LOG.D ("TAG", "Max memory is" + MaxMemory + "KB");
therefore, when displaying high-resolution images, it is best to compress the images first. The compressed picture size should be similar to the size of the control used to show it, and displaying a large picture on a small ImageView will not have any visual benefit, but it will take up quite a lot of our valuable memory and may have a negative impact on performance. Let's take a look at how to properly compress a large picture so that it can be displayed at the best size while preventing OOM from appearing.
BitmapfactoryThis class provides a number of parsing methods(Decodebytearray,decodefile, Decoderesourcewait)used to createBitmapobject, we should choose the appropriate method according to the source of the picture. LikeSdthe pictures in the card can be usedDecodeFilemethod, the pictures on the network can be usedDecodestreammethod, the picture in the resource file can be usedDecoderesourcemethod. These methods will attempt to create aBitmapallocates memory, it can easily causeOOMappear. Each of these parsing methods provides an optionalBitmapfactory.optionsparameter, set the parameter'sInjustdecodeboundsproperty is set toTrueYou can let the parsing method be disabled forBitmapallocates memory, and the return value is no longer aBitmapobject, butNull. AlthoughBitmapis aNull, butBitmapfactory.optionsof theOutwidth,Outheightand theOutmimetypeproperties are assigned values. This technique allows us to get the image's long and wide values before loading the image andMimetype to compress the picture as appropriate. As shown in the following code:
[Java] View plaincopy
Bitmapfactory.options Options = Newbitmapfactory.options ();
Options.injustdecodebounds = true;
Bitmapfactory.decoderesource (Getresources (), r.id.myimage, options);
int imageheight = Options.outheight;
int imagewidth = Options.outwidth;
String ImageType =options.outmimetype;
to avoid OOM exception, it is best to parse each picture when the size of the first check, unless you very much trust the source of the picture, to ensure that these images will not exceed your program's available memory.
Now that the size of the picture is known, we can decide whether to load the entire picture into memory or load a compressed version of the image into memory. Here are a few things we need to consider:
Estimate the memory required to load the entire picture.
How much memory you are willing to provide in order to load this picture.
The actual size of the control used to show this picture.
The screen size and resolution of the current device.
For example, your ImageView only the size of 128*96 pixels, just to display a thumbnail, it is not worthwhile to load a picture of 1024x768 pixel completely into memory.
So how do we compress the image? this can be achieved by setting the value of Insamplesize in Bitmapfactory.options. For example, we have a picture of 2048*1536 pixels, Set the value of Insamplesize to 4, you can compress this image into 512*384 pixels. Originally load this picture need to occupy 13M of memory, compressed only need to occupy 0.75M ( Assuming the picture is the argb_8888 type, that is, each pixel occupies 4 Bytes ). The following method calculates the appropriate insamplesize value according to the width and height of the incoming :
[Java] View plaincopy
public static intcalculateinsamplesize (Bitmapfactory.options Options,
int reqwidth, int reqheight) {
the height and width of the source picture
Final int height = options.outheight;
Final int width = options.outwidth;
int insamplesize = 1;
if (Height > Reqheight | | width > reqwidth) {
calculates the ratio between the actual width and the target width
Final int heightratio = Math.Round ((float) height/(float) reqheight);
Final int widthRatio = Math.Round ((float) width/(float) reqwidth);
Select width and high school minimum ratio as the value of the insamplesize, so that the final picture width and height can be guaranteed
must be greater than or equal to the width and height of the target.
Insamplesize = HeightRatio < WidthRatio? Heightratio:widthratio;
}
return insamplesize;
}
using this method, first you will Bitmapfactory.options the injustdecodebounds property is set to trueto parse the picture once. the bitmapfactory.options is then passed along with the desired width and height to the Calculateinsamplesize method, so that the appropriate insamplesize can be obtained. the value. Then parse the picture again, use the newly obtained insamplesize value, and set the Injustdecodebounds to false, you can get the compressed picture.
[Java] View plaincopy
public static Bitmapdecodesampledbitmapfromresource (Resources res, int resId,
int reqwidth, int reqheight) {
The first resolution sets injustdecodebounds to Trueto get the picture size
Final Bitmapfactory.options Options = new Bitmapfactory.options ();
Options.injustdecodebounds = true;
Bitmapfactory.decoderesource (res, resId, options);
call the method defined above to calculate the insamplesize value
Options.insamplesize = calculateinsamplesize (options, reqwidth,reqheight);
parse the picture again using the obtained insamplesize value
Options.injustdecodebounds = false;
Return Bitmapfactory.decoderesource (res, resId, options);
}
The following code is very simple to compress any picture into a 100*100 thumbnail and show it on the ImageView .
[Java] View plaincopy
Mimageview.setimagebitmap (
Decodesampledbitmapfromresource (Getresources (), R.id.myimage, 100,100));
Using Picture caching technology
in your application's The UI interface loading a picture is a very simple thing, but when you need to load a lot of pictures on the interface, the situation becomes complicated. In many cases (such as using widgets such as ListView, GridView, or viewpager ), images displayed on the screen can be continuously increased through events such as sliding screens, eventually resulting in OOM.
In order to ensure that the memory usage is always maintained in a reasonable range, the image removed from the screen is usually recycled. The garbage collector will also assume that you no longer have a reference to these pictures to perform GC operations on them . Using this approach to solve the problem is very good, but in order to allow the program to run quickly, in the interface to quickly load the picture, you have to consider that some pictures are recycled, the user then re-slide it into the screen this situation. It is a performance bottleneck to reload the images that have just been loaded, and you need to find a way to avoid the situation.
This time, the use of memory caching technology can be a good solution to this problem, it allows the component to quickly reload and process the picture. Let's take a look at how memory caching technology can be used to cache images so that your application will be able to improve responsiveness and fluency when loading many images.
Memory Caching technology provides quick access to images that consume valuable memory from applications. The most core of these classes is LruCache ( This class is provided in the ANDROID-SUPPORT-V4 package) . This class is ideal for caching images, and its main algorithm is to store recently used objects in Linkedhashmap with strong references , and to remove the least recently used objects from memory before the cached value reaches a predetermined value.
in the past, we often used an implementation of a very popular memory caching technique, namely soft or weak reference (SoftReference or WeakReference) . However, this is no longer recommended because , starting with Android 2.3 (API level 9) , the garbage collector is more inclined to reclaim objects holding soft or weak references, which makes soft and weak references less reliable. In addition,in Android 3.0 (API level) , the image data is stored in local memory, so it cannot be released in a predictable way, which poses a potential risk for the application's memory overflow and crashes.
in order to be able to select a suitable cache size for the LruCache, There are several factors that should be taken into account, such as:
How much memory can your device allocate for each application?
How many pictures can be displayed on the device screen at a time? How many images need to be preloaded, as it is possible to be displayed on the screen soon?
What is the screen size and resolution of your device? An ultra-high-resolution device, such as a Galaxy nexus, requires more cache space than a lower-resolution device, such as a Nexus S, when holding the same number of images.
The size and size of the picture, and how much memory space each image occupies.
how often are the images accessed? Will there be some images that are more frequently accessed than other images? If so, you might want to have some images reside in memory, or use multiple LruCache objects to distinguish different groups of pictures.
Can you maintain a good balance between quantity and quality? In some cases, it is more effective to store multiple low-pixel images, while loads in the background to load high-resolution images.
and not a specified cache size can satisfy all applications, which is up to you. You should analyze the usage of the program's memory and then work out a suitable solution. A cache space that is too small can cause images to be released and reloaded frequently, which does not benefit. A cache space that is too large can still cause java.lang.OutOfMemory exceptions.
here is a use examples of LruCache to cache images:
[Java] View plaincopy
Private Lrucache<string, bitmap>mmemorycache;
@Override
protected void OnCreate (bundlesavedinstancestate) {
gets the maximum amount of free memory that is used to exceed this value to cause a OutOfMemory exception.
LruCache passes through the constructor to the cache value, in kilobytes .
int maxmemory = (int) (Runtime.getruntime (). MaxMemory ()/1024);
1/8 with the maximum available memory value as the size of the cache.
int cacheSize = MAXMEMORY/8;
Mmemorycache = new lrucache<string, bitmap> (cacheSize) {
@Override
protected int sizeOf (String key, Bitmap Bitmap) {
Override this method to measure the size of each picture, returning the number of pictures by default.
return Bitmap.getbytecount ()/1024;
}
};
}
public void Addbitmaptomemorycache (Stringkey, Bitmap Bitmap) {
if (Getbitmapfrommemcache (key) = = null) {
Mmemorycache.put (key, bitmap);
}
}
Public Bitmap Getbitmapfrommemcache (stringkey) {
return Mmemorycache.get (key);
}
in this example, one-eighth of the memory allocated by the system to the application is used as the cache size. In high-profile handsets, this will probably have 4 megabytes (32/8) of cache space. A full-screen GridView is populated with 4 800x480 resolution images, which will probably take up 1.5 of Space (800*480*4). Therefore, this cache size can store images of 2.5 pages.
when the when a picture is loaded in the ImageView, it is first checked in the LruCache cache. If the corresponding key value is found, the ImageView is updated immediately , otherwise a background thread is opened to load the image.
[Java] View plaincopy
public void LoadBitmap (int resId, Imageviewimageview) {
Final String ImageKey = string.valueof (resId);
Final Bitmap Bitmap = Getbitmapfrommemcache (ImageKey);
if (bitmap! = null) {
Imageview.setimagebitmap (bitmap);
}else {
Imageview.setimageresource (R.drawable.image_placeholder);
Bitmapworkertask task = new Bitmapworkertask (ImageView);
Task.execute (RESID);
}
}
Bitmapworkertask also puts the key-value pairs of the newly loaded pictures into the cache.
[Java] View plaincopy
Class Bitmapworkertask Extendsasynctask<integer, Void, bitmap> {
load the picture in the background.
@Override
Protected Bitmap doinbackground (Integer ... params) {
Final Bitmap Bitmap = Decodesampledbitmapfromresource (
Getresources (), params[0], 100,100);
Addbitmaptomemorycache (String.valueof (Params[0]), bitmap);
return bitmap;
}
android-efficient loading of pictures experience sharing