Minoru
Minoru

Reputation: 1730

Bitmap.compress doesn't decrease the Byte count

I need to compress an image to send it to my server. I am trying to do it this way:

private Bitmap compressImage(Bitmap bitmapImg){
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    bitmapImg.compress(Bitmap.CompressFormat.JPEG, 50, out);
    Bitmap compressed = BitmapFactory.decodeStream(new ByteArrayInputStream(out.toByteArray()));

    return compressed;
}

But when I compare the Byte count of the original Bitmap object and the compressed one, I get the same number:

Log.e("UNCOMPRESSED", Integer.toString(mBitmapImg.getByteCount()));
E/UNCOMPRESSED: 23970816
Log.e("COMPRESSED", Integer.toString(compressedBitmapImg.getByteCount()));
E/COMPRESSED: 23970816

How can I fix this to have a smaller file?

Upvotes: 3

Views: 955

Answers (2)

Rohan Stark
Rohan Stark

Reputation: 2396

You can change your bitmap format to RGB_565 from ARGB_8888. That'll reduce your bitmap's memory footprint to half, but, would lead to loss of quality as well. Unfortunately, that's the most you can do with Bitmap.

Having said that, the compression method that you're using should work fine for most situations. It's also the advocated method for a number of platforms. An example for Firebase is this.

Upvotes: 1

CommonsWare
CommonsWare

Reputation: 1006869

But when I compare the Byte count of the original Bitmap object and the compressed one, I get the same number:

The size of a Bitmap in memory is based only on its resolution (width and height in pixels) and bit depth (the number of bytes per pixel, for controlling how many colors can be used per pixel).

How can I fix this to have a smaller file?

You do not have a file. You have a Bitmap object in memory. An image file is usually stored in a compressed form. In particular, this is true for JPEG, PNG, WebP, and GIF, the four major image formats used in Android. So, for example, out.toByteArray() will be smaller than 23,970,816 bytes.

Moreover, you are not sending a Bitmap to the server. You are sending an image to the server. You need to read the documentation for the server, or talk to the server developers, to determine what image format(s) they support and how to send the image to the server (ideally, something efficient like an HTTP PUT).

If you want to reduce the in-memory size of the Bitmap, scale it to a lower-resolution image (e.g., via createScaledBitmap()).

Upvotes: 4

Related Questions