1

There's a 2MB limit on the server where I need to upload an image.

I'm using this method to downsample a Bitmap Strange out of memory issue while loading an image to a Bitmap object

within this method

public InputStream getPhotoStream(int imageSizeBytes) throws IOException {
        int targetLength = 1500;
        ByteArrayOutputStream photoStream;
        byte[] photo;
        Bitmap pic;
        final int MAX_QUALITY = 100;
        int actualSize = -1;
        do {
            photo = null;
            pic = null;
            photoStream = null;

            //this calls the downsampling method
            pic = getPhoto(targetLength);

            photoStream = new ByteArrayOutputStream();
            pic.compress(CompressFormat.JPEG, MAX_QUALITY, photoStream);
            photo = photoStream.toByteArray();
            actualSize = photo.length;
            targetLength /= 2;
        } while (actualSize > imageSizeBytes);
        return new ByteArrayInputStream(photo);
}

This throws OutOfMemoryError on the second iteration. How could I downsample the image below a certain size limit?

Community
  • 1
  • 1
siamii
  • 23,374
  • 28
  • 93
  • 143

2 Answers2

1

I think the problem is happening because you are compressing the image to a in memory representation, you need to free up that memory before you try to compress again.

You need call close() in the photoStream before trying again in order to free up resources. Also toByteArray() makes a copy of the stream in memory that you have to free up later, why don't you just use the photoStream.size() to check for the file size?

I can post some code if you need.

renam.antunes
  • 761
  • 1
  • 5
  • 11
1

Instead of this:

pic = null;

Do this:

if (pic!=null)
    pic.recycle();
pic = null

If you simply set the bitmap object to null the memory it occupied isn't released immediately. In the second case you are explicitly telling the OS you are done with the bitmap and its okay to release its memory.

Also consider using a compression quality of 90 instead of 100, I believe that will reduce the resulting file size quite a bit.

slayton
  • 20,123
  • 10
  • 60
  • 89