Resize a large bitmap file to scaled output file on Android

Manuel picture Manuel · Jul 26, 2010 · Viewed 226.7k times · Source

I have a large bitmap (say 3888x2592) in a file. Now, I want to resize that bitmap to 800x533 and save it to another file. I normally would scale the bitmap by calling Bitmap.createBitmap method but it needs a source bitmap as the first argument, which I can't provide because loading the original image into a Bitmap object would of course exceed the memory (see here, for example).

I also can't read the bitmap with, for example, BitmapFactory.decodeFile(file, options), providing a BitmapFactory.Options.inSampleSize, because I want to resize it to an exact width and height. Using inSampleSize would resize the bitmap to 972x648 (if I use inSampleSize=4) or to 778x518 (if I use inSampleSize=5, which isn't even a power of 2).

I would also like to avoid reading the image using inSampleSize with, for example, 972x648 in a first step and then resizing it to exactly 800x533 in a second step, because the quality would be poor compared to a direct resizing of the original image.

To sum up my question: Is there a way to read a large image file with 10MP or more and save it to a new image file, resized to a specific new width and height, without getting an OutOfMemory exception?

I also tried BitmapFactory.decodeFile(file, options) and setting the Options.outHeight and Options.outWidth values manually to 800 and 533, but it doesn't work that way.

Answer

Justin picture Justin · Jul 26, 2010

No. I'd love for someone to correct me, but I accepted the load/resize approach you tried as a compromise.

Here are the steps for anyone browsing:

  1. Calculate the maximum possible inSampleSize that still yields an image larger than your target.
  2. Load the image using BitmapFactory.decodeFile(file, options), passing inSampleSize as an option.
  3. Resize to the desired dimensions using Bitmap.createScaledBitmap().