问题
I have a PNG image of 168.2KB and 1991x1756 and tried to import it into a Bitmap
using BitmapFactory.decodeStream()
. The problem is that I run into OutOfMemoryError
where the Bitmap
size ends up being 13,657KB.
What I don't understand is why is the file so big after the import and how to mitigate this.
Seems that this OutOfMemoryError
issue is very common with decoded Bitmap
images but can't find a way to fix it. Any ideas?
Bitmap bitmap = BitmapFactory.decodeStream(inputStream, null, bitmapOptions);
E/AndroidRuntime(10744): java.lang.OutOfMemoryError: bitmap size exceeds VM budget(Heap Size=7815KB, Allocated=3279KB, Bitmap Size=13657KB)
回答1:
A png-file is highly compressed, meaning that the file size on disk is much smaller than it would be when all the data it contains is loaded into memory.
A bitmap is a very simple representation of an image, where every pixel is represented by a value. The size of this value depends on the current settings (you may have heard of 32-bit images, 16 bit images or 8 bit images which are some common sizes).
To calculate the true size of an image represented as a bitmap you have to calculate the number of pixels, and multiply this with how many bits you have for each pixel.
Your image is 1991x1756 pixels (3 496 196 pixels in total). If you load the bitmap using ARGB_8888 format (one byte for each color/alpha channel = 4 bytes per pixel) you end up with 3 496 196 * 4 =
13 984 784
bytes.
You can reduce the total size by using fewer bytes/channel (RGB_565 for example) although this also reduces the quality of your image. A better option would most likely be to reduce the size of your images, or import them using the inSampleSize parameter in your BitmapFactory.Options
to load a smaller image.
回答2:
I believe the PNG image is heavily compressed, but bitmaps in android are not compressed as there are 4 bytes per pixel (ARGB)
so 1991 * 1756 * (4 bytes) is about 13657 KB
So try using a smaller image or insample size Options for bitmap options to reduce the size.
Take a look at this post: Decoding bitmaps in Android with the right size
来源:https://stackoverflow.com/questions/10156675/bitmapfactory-decodestream-returns-a-bitmap-100-times-more-than-original