Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android how to scale an image with BitmapFactory Options

Tags:

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

like image 967
saarraz1 Avatar asked Feb 20 '12 12:02

saarraz1


2 Answers

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.

like image 130
jbowes Avatar answered Sep 21 '22 15:09

jbowes


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.

like image 41
Jave Avatar answered Sep 19 '22 15:09

Jave