Android bitmap Those things how to optimize memory

Source: Internet
Author: User

the preface:"Ann has wide summer tens of thousands, the great scholars all over the world Smile Solutions"- du Fu. In the park to live in the friends are likely to encounter the problem of renting a house (local tyrants Please ignore), find a house is really definitely work, also time consuming, occupy my valuable blog time, no way, who let we have no money also want to live better, hard to earn money!!! The above to complain, now get to the point. the previous blog "Bitmap The memory occupancy calculation and loading considerations", wrote bitmap basic knowledge and the use of bitmap need to know the considerations, this blog I will write in the Android app bitmap created and loaded.

1, bitmapfactory use:


When it comes to the loading of pictures it must be said Bitmapfactory, see the name of his role, is a production of bitmap factory, is its some factory methods:


650) this.width=650; "src=" http://img.blog.csdn.net/20150420125033927 "style=" border:none; "/>


650) this.width=650; "src="/e/u261/themes/default/images/spacer.gif "style=" Background:url ("/e/u261/lang/zh-cn/ Images/localimage.png ") no-repeat center;border:1px solid #ddd;" alt= "Spacer.gif"/>

You can see that bitmapfactory can use arrays that store bitmap data, bitmap resources Id,bitmap files, and so on as data sources to create bitmap objects, depending on which data source is available in your program. Each of these methods provides two methods for each data source, here you need to pay attention to the Bitmapfacotry.options parameter, it is the inner class of bitmapfactory, there are some member variable meaning need to remember, the following is said.

2, bitmapfacotry.options the injustdecodebounds parameter use:

In order to save memory, in many cases the original image will be scaled processing, according to the size of the control to deal with the corresponding size of the picture, then use Bitmapfactory to create bitmap, in many cases will use the following code:

Bitmapfactory.options Options = new Bitmapfactory.options (); Options.injustdecodebounds =true; Bitmapfactory.decoderesource (Getresources (), r.id.myimage, options); int imageheight = Options.outheight;int ImageWidth = Options.outwidth; String imageType = Options.outmimetype;

Notice the optionsin the above. Injustdecodebounds = True of the Injustdecodebounds parameter, in order to avoid my translation inaccurate I'm going to post it here first Google's original: If set to True, the decoder will return Null (no bitmap), but the out ... fields would still be set, allowing the caller to query the bitmap without have to Alloc Ate the memory for its pixels. In my words, the memory is not allocated to this bitmap pixel area in decode, except for the other information bitmap the difference. This makes a lot of sense, you have not consumed the memory and get the information of the picture, for your next picture processing to provide help.

3, bitmapfacotry.options the insamplesize parameter use:

The previous step you have obtained the original size of the picture, the next step is to zoom the original image to the size you want, can be set by the Insamplesize parameter, Google's original explanation is: If set to a value > 1, requests the Decoder to subsample the original image, returning a smaller image to save memory. The sample size is the number of pixels in either dimension this correspond to a single pixel in the decoded bitmap. For example, insamplesize = = 4 Returns an image which is the width/height of the original, and 1/16 the number of pixel S. Any value <= 1 is treated the same as 1. Note:the decoder would try to fulfill this request, but the resulting bitmap may has different dimensions that precisely What has been requested. Also, powers of 2 is often faster/easier for the decoder to honor. (Whether you do not read English documents I still want to paste the original Google, my English is bad, translation is not necessarily accurate), probably mean this Parameters can adjust the memory you need in the decode original image, a bit like the sampling rate, will throw away some pixels, the value is greater than 1 number, the power of 2 is more advantageous to the operation. As an example: when   insamplesize = = 4   will return a size (length and width) is the original size 1/4, the pixel is the original 1/16 picture. How is this value calculated?

Public static int calculateinsamplesize (             bitmapfactory.options options,int reqwidth,int reqheight) {     // Raw height and width of image    finalint  height = options.outheight;    finalint width = options.outwidth;     int insamplesize =1;    if (height >  reqheight | |  width > reqwidth) {        finalint halfheight  = height /2;        finalint halfwidth =  width /2;        // calculate the largest  insamplesize value that is a power of 2 and keeps both         // height and width larger than the  Requested height and width.        while ((halfHeight  / insamplesize) > reqHeight                 && (halfwidth / insamplesize) > reqwidth) {             inSampleSize *=2;         }    }    return insamplesize;}

options . in justdecodebounds  = true, get to the picture parameter and then set to False, this is the technique of decode, the following will put the full code, can be used as a tool method:

Public static bitmap decodesampledbitmapfromresource (resources res,int resid,         int reqwidth,int reqheight) {    //  First decode with inJustDecodeBounds=true to check dimensions     finalbitmapfactory.options options =newbitmapfactory.options ();     Options.injustdecodebounds =true;    bitmapfactory.decoderesource (Res, resId,  options);    // calculate insamplesize     Options.insamplesize = calculateinsamplesize (options, reqwidth, reqheight);     // Decode bitmap with inSampleSize set     Options.injustdecodebounds =false;    returnbitmapfactory.decoderesource (res,  resid, options);}

The above method comes from Google's website, no need to make changes, this is the programmer's take doctrine bar, the key is to know why so write. Here is a method that I wrote myself to use directly as a tool.

    /**     *  compress the image, mainly to solve the problem that the control is showing too much memory and causing oom problems. Generally compressed picture size should be similar to the size of the controls used to show it .     *     *  @param   context  context      *  @param  resId  picture Resources id      *  @param  reqWidth  width of desired compression      *  @param  reqHeight  Desired compression height      *  @return   Compressed picture      */     public static bitmap compressbitmapfromresourse (Context context, int  resid, int reqwidth, int reqheight)  {         final bitmapfactory.options options = new bitmapfactory.options ();         /*         *  first time resolution, Injustdecodebounds set to True,         *  is forbidden to allocate memory for bitmap, although the bitmap return value is empty, you can get the picture size           */        options.injustdecodebounds  = true;        bitmapfactory.decoderesource ( Context.getresources (),  resid, options);        final  Int height = options.outheight;        final int  width = options.outwidth;        int insamplesize  = 1;        if  (height > reqheight | |  width > reqwidth)  {             final int heightratio = math.round (float)  height /  (float)   Reqheight);              final int widthratio = math.round (float)   width /  (float)  reqwidth);             inSampleSize = heightRatio < widthRatio ? heightRatio :  widthratio;        }         options.insamplesize = insamplesize;        //  Parse the picture again using the computed insamplesize value         options.injustdecodebounds =  false;        return bitmapfactory.decoderesource ( Context.getresources (),  resid, options);     }

The above is the bitmap in the Android loaded into the memory of some of the small tricks, we are not in the future can be very good application, to avoid the loading of images caused by the problem of Oom? If you have a better way to give me a message or add my public number:coder_online. We all study together, make progress together, making money no longer worrying about the house. You can easily scan the following QR code to add:

650) this.width=650; "Src=" HTTP://IMG.BLOG.CSDN.NET/2 0150323142905787 "style=" border:none;font-family:arial;line-height:26px;font-size:16px;font-weight:bold; "/>


This article is from the "8646004" blog, please be sure to keep this source http://8656004.blog.51cto.com/8646004/1636329

Android bitmap Those things how to optimize memory

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.