Android effectively handles bitmap and reduces memory

Source: Internet
Author: User

Android effectively handles bitmap and reduces memory

Pictures may be of different sizes. In many cases, the size of the picture will exceed the size we need. For example, our camera app, the size of the photos we took is much larger than the size of the screen display.

If your application is limited to memory usage, it is obvious that you will choose to load a low-resolution image. This low-resolution picture should match the size of the screen. Higher-resolution images do not provide any visible benefits, but still consume valuable memory, and additional performance overhead due to additional dynamic scaling.

This article teaches you to modify a large image by loading a sample of a small size, without exceeding the memory limit of the application.

Original Address http://wear.techbrood.com/training/displaying-bitmaps/load-bitmap.html

get the type size of a pictureBitmapfactory This class provides several decoding methods (for example: Decodebytearray (), DecodeFile (), Decoderesource ()); When we load the image, there may be many sources of images, We choose a suitable method to decode the image. Here's how to reallocate memory for a bitmap that has already been created, which is a good way to resolve a memory overflow (OutOfMemory Exception) problem. Each decoding method has a number of identity bits that you can configure to implement bitmapfactory.options these identity bits. When setting the Injustdecodebounds property to True, we do not allocate memory when decoding, the returned bitmap is null, but we set the Outwidth,outheight and Outmimetype. This technique can be pre-acquired to bitmap size data and type data.
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;
To avoidjava.lang.OutOfMemoryexceptions,Before decoding the picture, check the size of the bitmap beforehand, unless you have absolute certainty that your bitmap is of the right size and within the memory limit.
load scaled picture to memoryNow that we know the size of the image, we can decide whether to use the image of that size or use another sample. There are a number of factors we should pay attention to:
    • Estimating the memory consumed by the entire image loading
    • The amount of memory you can receive and the memory your program can use
    • The size of the ImageView or other UI components that you put in the picture
    • The size of the screen
For example, we don't deserve to put a picture of 1024x768 pixel in the 128*96 pixel thumbnail control (ImageVIew). We have to use a smaller sample of the image to load into memory and set Insamplesize to true in Bitmapfactory.options. For example, we want to decode a picture of 2048*1536 to only 1/4 size picture 512*384, loaded into memory for sale year only 0.75MB size, far Xiaoyu original 12MB size (using argb_8888 channel picture). Here's a way to calculate a sample image, depending on the width and height of the target image:
public static int calculateinsamplesize (            bitmapfactory.options Options, int reqwidth, int reqheight) {    //Raw Hei Ght and width of image    final int height = options.outheight;    Final int width = options.outwidth;    int insamplesize = 1;    if (Height > Reqheight | | width > reqwidth) {        final int halfheight = HEIGHT/2;        Final int halfwidth = WIDTH/2;        Calculate the largest insamplesize value is a power of 2 and keeps both        //height and width larger than the RE quested height and width.        while ((halfheight/insamplesize) > Reqheight                && (halfwidth/insamplesize) > Reqwidth) {            Insamp Lesize *= 2;        }    }    return insamplesize;}

Note:a power of calculated because the decoder uses A final value by rounding down to the nearest power of T Wo, as per the insamplesize documentation.

When we use this method, we first set theinJustDecodeBoundsto True, then we calculate the value of Insample, then set Injustdecodebounds to False, and finally 。 decode the picture
public static Bitmap Decodesampledbitmapfromresource (Resources res, int resId,        int reqwidth, int reqheight) {    // First decode with injustdecodebounds=true to check dimensions    final bitmapfactory.options Options = new Bitmapfactory . 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;    Return Bitmapfactory.decoderesource (res, resId, options);}

This approach can help us to easily and efficiently load a 100*100 thumbnail image:
Mimageview.Setimagebitmap(Decodesampledbitmapfromresource(getresources(),R.ID.MyImage,  -,  -));

You can also decode a picture obtained from another path in the same way, by using theBitmapFactory.decode*As need. here are a few from the Android developer above translation, it feels very useful, add a concern, (*^__^*) hehe

Android effectively handles bitmap and reduces 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.