0

I'm trying to load a picture from the gallery into a bitmap using this code:

Bitmap myBitmap = Bitmap.createScaledBitmap(BitmapFactory.decodeFile(adress), (int)viewWidth/2, (int)viewHeight/2, false);

where 'adress' is the adress of the picture in the gallery. This works fine on my Galaxy Note 1, android version 2.3.6, but crashes due to 'out of memory' on my Galaxy 2, android version 4.1.2

Am I doing something wrong here? Is there a way to get a scaled bitmap? The resulting bitmap (when this does work) is a bit smudged due to scaling, but I don't mind. Thanks!!!

n00b programmer
  • 2,671
  • 7
  • 41
  • 56
  • See http://developer.android.com/training/displaying-bitmaps/load-bitmap.html – devnull Jul 19 '13 at 12:51
  • possible duplicate of [Android Bitmap.createScaledBitmap throws java.lang.OutOfMemoryError mostly on Jelly Bean 4.1](http://stackoverflow.com/questions/15552076/android-bitmap-createscaledbitmap-throws-java-lang-outofmemoryerror-mostly-on-je) – devnull Jul 19 '13 at 12:52

2 Answers2

2

use this method

    Bitmap bm=decodeSampledBitmapFromPath(src, reqWidth, reqHeight);

Implementation-

     public int calculateInSampleSize(BitmapFactory.Options options,
        int reqWidth, int reqHeight) {

    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 1;

    if (height > reqHeight || width > reqWidth) {
        if (width > height) {
            inSampleSize = Math.round((float) height / (float) reqHeight);
        } else {
            inSampleSize = Math.round((float) width / (float) reqWidth);
        }
    }
    return inSampleSize;
}

public Bitmap decodeSampledBitmapFromPath(String path, int reqWidth,
        int reqHeight) {

    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(path, options);

    options.inSampleSize = calculateInSampleSize(options, reqWidth,
            reqHeight);

    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;
    Bitmap bmp = BitmapFactory.decodeFile(path, options);
    return bmp;
}

}

T_V
  • 17,440
  • 6
  • 36
  • 48
  • this gives me the bitmaps in their original scale. I need the images to fill the necessary space, even though it means getting stretched – n00b programmer Jul 21 '13 at 20:53
0

this is directly your answer - you need to calculate sizes first and then fetch the image in the correct size

Lukas Olsen
  • 5,294
  • 7
  • 22
  • 28