0

I'm trying to compress a bitmap with JPG compression function.

This is my piece of code:

 ByteArrayOutputStream out = new ByteArrayOutputStream();
 originalBitmap.compress(Bitmap.CompressFormat.JPEG, 80, out);
 byte[] newArray = out.toByteArray();
 Bitmap compressed = BitmapFactory.decodeByteArray(newArray, 0, newArray.length);

The strange behavior is that if I change the compression factor (ie. from 80 to 50) the size of the "out" array will change.... but the bitmap "compressed" remain always with the same byte number as the "originalBitmap".

Someone can explain to me why?!?

Thanks in advance...

Blasco73
  • 2,980
  • 2
  • 24
  • 30

1 Answers1

3

The amount of bytes that a Bitmap takes is: X * Y * D, where:

  • X is the width, in pixels
  • Y is the height, in pixels
  • D is the bit depth, in bytes per pixel, which by default is 4

It does not matter whether the Bitmap was loaded from a JPEG, a PNG, a WebP, or anything else. The number of bytes is determined solely from the resolution (width times height) and the bit depth.

So, in your case, you are successfully creating a Bitmap with the same number of bytes as before, just with a bit fuzzier output.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • Ok. I've understood what you mean! Can you suggest me a good way to compress a bitmap? – Blasco73 May 24 '17 at 14:33
  • @Blasco73: I do not know what you mean by "compress a bitmap". If you mean "create a smaller bitmap that takes up less memory", use `createScaledBitmap()` on your original `Bitmap`. – CommonsWare May 24 '17 at 14:37
  • I mean a bitmap (however an image) with fixed width and height but with a variable compress ratio! – Blasco73 May 24 '17 at 14:39
  • 1
    @Blasco73: In memory, that is not possible, as I covered in my answer. You are welcome to save a bitmap to *disk* in a compressed format (JPEG, PNG, WebP, etc.). – CommonsWare May 24 '17 at 14:51
  • Yes I think that this is the solution (not elegant): save in a compressed format and reload it. Thanks – Blasco73 May 24 '17 at 14:53
  • @Blasco73: No. Reloading it will give you a `Bitmap` which takes the same amount of memory as it did originally. This is what you are doing in your question. – CommonsWare May 24 '17 at 15:12