简体   繁体   中英

Memory heap growth with bitmap

I am selecting a picture from gallery and I display it in an ImageView. However when I run it, I can see HUGE (up to 60MB) of Heap growth.

Here is the code:

    else if(requestCode == PICK_IMAGE && resultCode == RESULT_OK){             

        Uri selectedImage = data.getData();
        try {
            img = (Bitmap)MediaStore.Images.Media.getBitmap(
                    this.getContentResolver(), 
                    selectedImage);


        } catch (FileNotFoundException e) {
            Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        ImgContainer.setImageBitmap(img);       
        img.compress(Bitmap.CompressFormat.PNG, 100, boas);
        byteArray = boas.toByteArray();     
        try {
            boas.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

ALL variables have been initialized properly in the beginning of the class, so this is NOT the issue .

I appreciate your time and help.

img = (Bitmap)MediaStore.Images.Media.getBitmap(
                    this.getContentResolver(), 
                    selectedImage);

everytime ur creating new object and assgning it to img. changing it may work.

Edit :

// this can be ur singleton class

public class ImageHelper {

    private static ImageHelper imageHelper;

        private Bitmap imageBitmap;

        private ImageHelper() {


          imageBitmap = //source of ur image

        }

        public static ImageHelper getInstance() {
        if(imageHelper==null) {
            imageHelper = new ImageHelper();
        }
        return imageHelper;
        }

        public Bitmap getImage() {

            return this.imageBitmap;
        }

}

By doing this , u will have only 1 object of ImageHelper which will hold only 1 copy of the image.

In case u have a diferent point to set the image, like after u pick from the gallery,

u can have a setter method or this,

public void setImage(Bitmap image) {
    this.imageBitmap = image;
}

Which u can call as

ImageHelper.getInstance().setImage(image);

From wherever u want to use it, u can do it by

ImageHelper.getInstance().getImage();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM