Ok, so If I'll do it like it's now in edited post, how can I "resize" the image to get rid of outOfMemory Exception ?
Aha! Now we are getting somewhere.
What you had, in a prior edit of your question, was:
- read the entire bitmap into a byte array
- write the entire bitmap into another byte array as a low-quality JPEG
- read the entire bitmap into a
Bitmap
, backed by yet a third byte array
This will result in your consuming ~2.1x the heap space of your current implementation, which is already giving you OutOfMemoryError
messages. The byte arrays from #1 and #3 above will be the same size, equal to:
width x height x 4
where the width and height are expressed in pixels.
To reduce your memory consumption, you need to do to things:
Read in the bitmap once, as your current code does.
Use BitmapFactory.Options
to control the decoding of the bitmap. In particular, use inSampleSize
to reduce the number of pixels in the resulting Bitmap
. Quoting the JavaDocs for inSampleSize
:
If set to a value > 1, requests the decoder to subsample the original image, returning a smaller image to save memory. The sample size is the number of pixels in either dimension that correspond to a single pixel in the decoded bitmap. For example, inSampleSize == 4 returns an image that is 1/4 the width/height of the original, and 1/16 the number of pixels. Any value <= 1 is treated the same as 1. Note: the decoder uses a final value based on powers of 2, any other value will be rounded down to the nearest power of 2.
This sample project demonstrates the use of inSampleSize
for various hardcoded values. The actual Bitmap
loading comes from:
private Bitmap load(String path, int inSampleSize) throws IOException {
BitmapFactory.Options opts=new BitmapFactory.Options();
opts.inSampleSize=inSampleSize;
return(BitmapFactory.decodeStream(assets().open(path), null, opts));
}
getPathFromURI()
? If it is what I think it is, get rid of it, as aUri
is not necessarily aFile
. – ChibaopenInputStream()
on aContentResolver
to read in the data at theUri
. – ChibaBitmap
object on the data represented by theUri
, just passstream
todecodeStream()
and get rid oftmp
, theByteArrayOutputStream
, and theByteArrayInputStream
. Bear in mind that the image may be too big for your heap space. – Chiba