Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bitmap.compress - isn't working

I'm trying to compress picture I've taken with the camera without scaling the image size.

I tried bitmap.compress, but it didn't worked. just to be sure I tried compressing on bitmap loaded from resource but still no success.

any ideas?

example code:

//load bitmap from resources:
bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.trolltunga);
Log.d("roee", "onImageCaptured: before compress = " + bitmap.getByteCount() + ", " + bitmap.getWidth() + ", " + bitmap.getHeight());

//compressing
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 50, bos);
Bitmap comp = BitmapFactory.decodeStream(new ByteArrayInputStream(bos.toByteArray()));
Log.d("roee", "onImageCaptured: after compress = " + comp.getByteCount() + ", " + comp.getWidth() + ", " + comp.getHeight());

log results:

D/roee: onImageCaptured: before compress = 10800000, 3000, 900
D/roee: onImageCaptured: after compress = 10800000, 3000, 900
like image 306
Roee Avatar asked Aug 23 '26 10:08

Roee


1 Answers

Short version: You compress the Bitmap and decompress it immediately afterwards

Long version:

A Bitmap is not compressed. It's a container class for an array of bytes that represents the image in full size, for faster drawing and processing.

It is often used to load a picture in another format, let's say JPEG into memory for displaying or editing and has several methods for directly loading or saving to other file formats.

One of those is compress which turns the uncompressed byte array in compressed file format (in your case JPEG) and then outputs it to a stream so you can save it to storage or something.

When you use BitmapFactory.decodeStream it reads the info in the stream, recognizes the file format and decodes it to an uncompressed byte array. Normally you would just use that to load an image form storage.

What you did here is take a Bitmap, compress it to JPEG (loosing some information) and then decode that JPEG to an uncompressed Bitmap again, which has the same resolution, thus the same number of bytes and same size in memory.

Solution: If you want to see if the compress worked, just measure the output stream size with bos.toByteArray().length

like image 134
Gumbo Avatar answered Aug 24 '26 23:08

Gumbo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!