0

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);

}
Jack
  • 1,825
  • 3
  • 26
  • 43
  • It appears that you are calling BitmapFactory.decodeFile twice. Which would load your image into memory twice. Take a look at: http://stackoverflow.com/questions/11681274/get-bitmap-width-and-height-without-loading-to-memory – Morrison Chang Jul 08 '15 at 05:51
  • I got this code from a tutorial ,can you check this if statement, and please make it correct if there is error.I could not understand the statement if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE) break; – Jack Jul 08 '15 at 05:55
  • o.inJustDecodeBounds = false; add this before BitmapFactory.Options o2 = new BitmapFactory.Options(); – Piyush Jul 08 '15 at 06:12

1 Answers1

0

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.

W3hri
  • 1,563
  • 2
  • 18
  • 31