This article first summarizes the relevant concepts of bitmap, and then through a practical problem to analyze the considerations of setting up bitmapfactory.options to reduce unnecessary memory usage and avoid oom.
First, the use of bitmap trick
Try not to use Setimagebitmap or Setimageresource or Bitmapfactory.decoderesource to set a large image, as these functions are completed decode, This is ultimately done through the Java layer CreateBitmap, which consumes more memory. Therefore, instead of using the Bitmapfactory.decodestream method first to create a bitmap, and then set it to ImageView Source,decodestream the biggest secret is that it directly invokes the JNI >> Nativedecodeasset () to complete the decode, eliminating the need to use the Java layer CreateBitmap, thus saving the Java layer of space.
If the config parameter is added to the read, the loaded memory can be reduced effectively, thereby effectively preventing the throw out of Memory exception. In addition, Decodestream directly take the picture to read the bytecode, not according to the machine's various resolutions to automatically adapt, after using the Decodestream, you need to configure the corresponding image resources in hdpi and mdpi,ldpi. Otherwise the same size (number of pixels) is the same on different resolution machines, and the displayed size is wrong.
BitmapFactory.Options.inPreferredConfig
* Alpha_8: Number 8, graphics parameters should be represented by a byte, should be a 8-bit bitmap
* argb_4444:4+4+4+4=16, the parameters of the graph should be represented by two bytes and should be a 16-bit bitmap.
* argb_8888:8+8+8+8=32, the parameters of the graph should be represented by four bytes and should be a 32-bit bitmap.
* rgb_565:5+6+5=16, the parameters of the graph should be represented by two bytes and should be a 16-bit bitmap.
*
* alpha_8,argb_4444,argb_8888 are transparent bitmaps, that is, the letter a represents transparency.
* argb_4444: means there are four parameters, namely A,r,g,b, each parameter is represented by 4bit.
* argb_8888: means there are four parameters, namely A,r,g,b, each parameter is represented by 8bit.
* rgb_565: means there are three parameters, R,g,b, and three parameters are 5bit,6bit,5bit respectively.
*
*
* BitmapFactory.Options.inPurgeable;
*
* If Inpurgeable is set to True, the bitmap created using Bitmapfactory
* Memory space used to store pixel can be recycled when system memory is low.
* When the app needs to access bitmap's pixel again (such as drawing bitmap or calling GetPixel),
* The system will call Bitmapfactory decoder again to regenerate the pixel array of bitmap.
* In order to re-decode the image, bitmap is able to access the raw data stored bitmap.
*
* When Inpurgeable is false, the pixel memory space of the created bitmap cannot be reclaimed.
* So bitmapfactory Decodebytearray to create a new bitmap object,
* Different devices have different memory, so the number of bitmap that can be created at the same time may vary.
* 200 bitmap enough to make most devices outofmemory error.
* When Ispurgable is set to True, the system is running out of memory,
* The memory space occupied by some bitmap can be reclaimed, and outofmemory errors are generally not seen.
Here is a code to read bitmap:
[Java]View Plaincopy
- Public Bitmap Readbitmap (context context, int resId) {
- Bitmapfactory.options opts = new Bitmapfactory.options ();
- Opts.inpreferredconfig = config.rgb_565;
- Opts.inpurgeable = true;
- Opts.ininputshareable = true;
- InputStream is = Context.getresources (). Openrawresource (ResId);
- return Bitmapfactory.decodestream (IS, null, opts);
- }
Ii. precautions for using bitmapfactory.options on Android4.4 systems
After upgrading the phone's Android system to 4.4 in the previous period, it was found that the previously developed app was running a very bad card and severely impacted the user experience. It was later found to be related to the underlying implementation of Bitmap.decodebytearray. This article will summarize the cause of the problem, I hope you can write code to pay attention to, because this problem once encountered, it takes a lot of time to find out why.
Our code can scale the image according to the density of the screen, so we use the largest picture resources, so that for any phone screen, the image will be compressed, without causing visual problems. Before decoding the image, you need to set the bitmapfactory.options, some of the code is as follows:
[Java]View Plaincopy
- bitmapfactory.options options = new bitmapfactory.options ();
- displaymetrics displaymetrics = context.getresources.getdisplaymetrics ();
Li class= "alt" >......  
- options.intargetdensity = displaymetrics.densitydpi;
- options.inscaled = TRUE;  
The
- //getbitmapdensity () sets the density that the picture will be displayed.
- options.indensity = getbitmapdensity ();
- ...
- bitmap bitmap = getbitmapfrompath (loadpath, options );
Options.intargetdensity represents the pixel density (the number of pixels per inch) that the target bitmap is about to be drawn to the screen. This property tends to be combined with options.indensity and options.inscaled to see if the target bitmap needs to be scaled. If this value is 0, then bitmapfactory.decoderesource (resources, int) and bitmapfactory.decoderesource (resources, int, android.graphics.BitmapFactory.Options) Decoderesourcestream (Resources, Typedvalue, InputStream, Rect, Bitmapfactory.options) intargetdensity is set with displaymetrics.densitydpi and other functions do not scale to bitmap.
Options.indensity represents the pixel density used by the bitmap. If this value is inconsistent with options.intargetdensity, the image is scaled. If set to 0, then Decoderesource (resources, int), Decoderesource (resources, int, android.graphics.BitmapFactory.Options), and Decoderesourcestream (Resources, Typedvalue, InputStream, Rect, bitmapfactory.options) will use the screen density value to set this parameter, other functions will not be scaled.
The magnification of the picture is calculated based on the intargetdensity/indensity.
The image we use is 640 * 1136, the encoding format is argb_8888, then the size is 640*1136*4=291k. Cell phone screen density is 480, then options.intargtetdensity for 480;indensity is set to 160. The size of the bitmap will be enlarged by 9 times times, and the size of the image should be 640*1136*4=26m after the photo is set. A total of 3 of these images were loaded in our app, so it's very easy to run a card.
But why Android4.4 the previous version did not have such a problem, for this we analyzed the source of Bitmap.decodebytearray ().
[Java]View Plaincopy
- /**
- * Decode an immutable bitmap from the specified byte array.
- *
- * @param data byte array of compressed image data
- * @param offset offset into imageData for where the decoder should begin
- * Parsing.
- * @param length The number of bytes, beginning at offset, to parse
- * @param opts Null-ok; Options that control downsampling and whether the
- * Image should be completely decoded, or just is size returned.
- * @return the decoded bitmap, or null if the image data could not being
- * Decoded, or, if OPTs is non-null, if opts requested only the
- * Size is returned (in Opts.outwidth and Opts.outheight)
- */
- public static Bitmap Decodebytearray (byte[] data, int offset, int length, Options opts) { /c3>
- if ((offset | length) < 0 | | Data.length < offset + length) {
- throw new ArrayIndexOutOfBoundsException ();
- }
- Bitmap BM;
- Trace.tracebegin (Trace.trace_tag_graphics, "Decodebitmap");
- try {
- BM = Nativedecodebytearray (data, offset, length, opts);
- if (BM = = Null && opts! = null && opts.inbitmap! = null) {
- throw New IllegalArgumentException ("problem decoding into existing bitmap");
- }
- Setdensityfromoptions (BM, opts);
- } finally {
- Trace.traceend (Trace.trace_tag_graphics);
- }
- return BM;
- }
We found that the function calls the local function Nativedecodebytearray (byte[] data, int offset, int length, Options opts) to parse the picture.
android4.4 the Dodecode function is not scaled according to density in the previous BitmapFactory.cpp Nativedecodebytearray (not all of the previous 4.4 codes are found, take 4.2 as an example):
Willscale This parameter determines whether it can be scaled, and because there is no incoming scale value into Dodecode, scales always uses the default value of 1.0f, so Willscale will always be false based on the default value, that is, bitmap will not be scaled.
android4.4 platform Nativedecodebytearray has not changed the method of Dodecode invocation, but changed the implementation of Dodecode function, especially the method of calculating Willscale.
Where the global variable goptions_scaledfieldid is the ID of the native layer of the Inscale variable bitmapfactory.options in the Java file,
Because scale = (float) targetdensity/density, the zoom speed is determined by the value of Intargetdensity and indensity two.
In the native layer, when scale is not equal to 1.0, the image is scaled, and the length-width scaling is as follows:
Well, just write here, you can check the previously written code, if there is based on the screen density loading bitmap parts, please run the app on 4.4 of the system to see the memory usage. The solution to the above problem is actually very simple, we can think about it.
Bitmap basic concepts and considerations for using Bitmapfactory on Android4.4 systems