22

I want to decode an image from the SD card with BitmapFactory.decodeFile(path, options).
I also want images that are larger than 2048x2048 pixels to be scaled down to at most 2048x2048 (maintaining the proportions).
I could do this manually after getting the bitmap, but that would require allocating a large amount of bytes in addition to the ones already allocated.
How should i set up my BitmapFactory.Options object to get that effect?
Thanks

saarraz1
  • 2,999
  • 6
  • 29
  • 44
  • Possible duplicate of [Resize a large bitmap file to scaled output file on Android](https://stackoverflow.com/q/3331527/608639) – jww Sep 02 '18 at 15:45

3 Answers3

13

Use BitmapFactory.Options.inSampleSize when you first load your image to get the size as close as possible to your target size, then use Bitmap.createScaledBitmap to scale to the exact size you want.

There's some code for this in this answer.

Community
  • 1
  • 1
jbowes
  • 4,062
  • 22
  • 38
6

Start by setting inJustDecodeBounds to true in your Options, this will give you the size of the image, without loading any of the image data.
If the image size is smaller then your max size, then just load it as usual.
If on the other hand, it is too big, use the inSampleSize to read a smaller bitmap.

Note: I don't think that the decoding does any filtering when using the inSampleSize, so you might lose some detail, but as your image size is so big (2048 px) I don't think this will cause any problems.

Jave
  • 31,598
  • 14
  • 77
  • 90
4

You can try something like this:

int imageWidth, imageHeight;

Bitmap result = Bitmap.createScaledBitmap(bitmapPicture,
                        imageWidth, imageHeight, false);

Here you can add your own width and height. bitmapPicture is the object of Bitmap. Let me know if this is of any help to you.

jbowes
  • 4,062
  • 22
  • 38
Shishir Shetty
  • 2,021
  • 3
  • 20
  • 35
  • 2
    Like i said, I am trying to avoid having to allocate another 2048x2048 pixels, but have the BitmapFactory do this automatically, because i'm very short on memory. Your method just allocates a new bitmap which is not what I want. Thanks for the reply though. – saarraz1 Feb 20 '12 at 12:26