Search code examples
androidandroid-imageviewandroid-imageandroid-bitmap

How to avoid Out of Memory Error while handling Imageviews


In my app i am selecting a picture from storage or taking a picture using camera and it will set in to an image view.When doing this i got Out of memory Error ,to avoid this I used this method.But it is not working,can anyone help to solve this issue .Or can anyone suggest any other method to handle this issue.

 public void decodeFile(String filePath) {
    // Decode image size
    BitmapFactory.Options o = new BitmapFactory.Options();
    o.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(filePath, o);

    // The new size we want to scale to
    final int REQUIRED_SIZE = 1024;

    // Find the correct scale value. It should be the power of 2.
    int width_tmp = o.outWidth, height_tmp = o.outHeight;
    int scale = 1;
    while (true) {
        if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE)
            break;
        width_tmp /= 2;
        height_tmp /= 2;
        scale *= 2;
    }

    // Decode with inSampleSize
    BitmapFactory.Options o2 = new BitmapFactory.Options();
    o2.inSampleSize = scale;
    bitmap = BitmapFactory.decodeFile(filePath, o2);

    imgView.setImageBitmap(bitmap);

}

Solution

  • I would suggest to use a library to handle the loading, caching and displaying of images. They are easy to use and you dont have to take care of image downsizing etc.

    In my projects i use the Universal Image Loader by nostra13. It is pretty easy to implement and offers a lot of features like memory and disk caching. You should give it a try.