Bitmapfactory.options solve the problem of memory overflow in Android loading picture
1. in the process of Android software development, picture processing is often encountered. When the picture is converted to bitmap, due to the size of the picture is not the same, when encountering a large picture will appear beyond the memory of the problem, in order to solve this problem the Android API provides bitmapfactory.options this class.
2. because Android has restrictions on the use of images, memory overflows if large images are loaded with a few megabytes. Bitmap will load all pixels (that is, the length x width) of the picture into memory, and if the image resolution is too large, it will directly cause memory oom, and only use Bitmapfactory.options to configure the relevant parameters when bitmapfactory loads the image to reduce the loaded pixels.
3. bitmapfactory.options Related parameters:
(1). Options.inpreferredconfig value to reduce memory consumption.
For example: The default value argb_8888 changed to rgb_565, saving half of memory.
(2). Set the options.insamplesize scale to compress the large picture.
(3). Set options.inpurgeable and ininputshareable: Allows the system to reclaim memory in a timely manner.
A: inpurgeable: When set to True, indicates that system memory can be reclaimed when set to false, indicating that it cannot be reclaimed.
B: ininputshareable: Set whether deep copy, used in conjunction with Inpurgeable, Inpurgeable is false, this parameter is meaningless.
(4). Use Decodestream instead of other methods.
Decoderesource,setimageresource,setimagebitmap and Other methods
4. Code section:
Public StaticBitmapGetbitmapfromfile(File file,intWidthintHeight) {Bitmapfactory.options opts =NULL;if(NULL! = File && file.exists ()) {if(Width >0&& height >0) {opts =NewBitmapfactory.options ();//Only returns the width and height of the picture, not returning a bitmap objectOpts.injustdecodebounds =true;//information is not stored in the bitmap, but is stored in the optionsBitmapfactory.decodefile (File.getpath (), opts);//Calculate picture zoom ratio Final intMinsidelength = math.min (width, height);//thumbnail size is a fraction of the original picture size. Do it according to business needs. Opts.insamplesize = Computesamplesize (opts, minsidelength, Width * height);//re-read the picture, note that the options.injustdecodebounds is now set back to FalseOpts.injustdecodebounds =false;//Set whether deep copy, used in combination with inpurgeableOpts.ininputshareable =true;When set to True, indicates that the system can be reclaimed when it is out of memory and set to false to indicate that it cannot be reclaimed. Opts.inpurgeable =true; }Try{returnBitmapfactory.decodefile (File.getpath (), opts); }Catch(OutOfMemoryError e) {E.printstacktrace (); } }return NULL; }
Bitmapfactory.options solve the problem of memory overflow in Android loading picture