开发者

Assigning bitmap to ImageView via setImageURI throws OutOfMemory exception

I have an activity with an empty ImageView and a button. After clicking the button, I display the device's media gallery, the user chooses an image that gets passed to the activity via an intent. I use the image's URI from the returned data and I populate the ImageView, like this:

private ImageView pic;

@Override
public void onCreate(Bundle savedInstanceState) 
{

      pic = (ImageView)findViewById(R.id.bbChildImage);

}

protected void onActivityResult(int requestCode, int resultCode, Intent data) 
{  

        if(resultCode == RESULT_OK)
        {   
            URI currImageURI = d开发者_StackOverflow中文版ata.getData();
            pic.setImageURI(currImageURI);
        }
}

Now, if I go to choose another image from the gallery, after the data is returned, I get a bitmap related OutOfMemory exception.

I figured out two ways to get rid of it. I either do this before assigning the URI:

((BitmapDrawable)pic.getDrawable()).getBitmap().recycle();

or instead of assigning the URI to the view, I retrieve the bitmap first, and then assign it, like this:

Bitmap thumbnail = MediaStore.Images.Media.getBitmap(this.getContentResolver(), currImageURI);
pic.setImageBitmap(thumbnail);

I am not sure which one is better. Also, if there are better ways, I would appreciate the feedback.

Thanks.


  1. Recycling is typically the way to go. If you don't need a bitmap, let the operating system know by recycling it.

  2. In addition to that, I would use the BitmapFactory to create the bitmap and use the options to shrink it upon loading. Don't make it bigger than the device's screen. That will save a lot of memory.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜