14

I am trying to reduce the size of images retrieved form the camera (so ~5-8 mega pixels) down to one a a few smaller sizes (the largest being 1024x768). I Tried the following code but I consistently get an OutOfMemoryError.

Bitmap image = BitmapFactory.decodeStream(this.image, null, opt);
int imgWidth = image.getWidth();
int imgHeight = image.getHeight();

// Constrain to given size but keep aspect ratio
float scaleFactor = Math.min(((float) width) / imgWidth, ((float) height) / imgHeight);

Matrix scale = new Matrix();
scale.postScale(scaleFactor, scaleFactor);
final Bitmap scaledImage = Bitmap.createBitmap(image, 0, 0, imgWidth, imgHeight, scale, false);

image.recycle();

It looks like the OOM happens during the createBitmap. Is there a more memory efficient way to do this? Perhaps something that doesn't require me to load the entire original into memory?

Sionide21
  • 2,202
  • 2
  • 21
  • 30

3 Answers3

17

When you decode the bitmap with the BitmapFactory, pass in a BitmapFactory.Options object and specify inSampleSize. This is the best way to save memory when decoding an image.

Here's a sample code Strange out of memory issue while loading an image to a Bitmap object

Community
  • 1
  • 1
EboMike
  • 76,846
  • 14
  • 164
  • 167
1

Here is a similar question that I answered and show how to go about dynamically loading the proper image size.

out of memory exception + analyzing hprof file dump

Community
  • 1
  • 1
toidiu
  • 965
  • 2
  • 12
  • 25
1

Are you taking the picture with the camera within your application? If so, you should set the picture size to a smaller one in the first place when they're being captured via android.hardware.Camera.Parameters.setPictureSize

Mathias Conradt
  • 28,420
  • 21
  • 138
  • 192
  • No, I am using the `android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI` to let the user select an image. – Sionide21 Jul 10 '10 at 15:46