Android Image size after compressed from bitmap is very large than original image load to bitmap-ThrowExceptions

Exception or error:

I am now a newbie to android programming.
I am very confused when processing with images.
I am now trying to load a jpeg image to bitmap and then convert bitmap to byte array and vice versa.
I am testing with the first case: load jpeg to bitmap and get byte array.
My input image 520 x 390 (24 bit color) 24KB JPEG.
My output byte array is ~ 290000 bytes ~ 290KB, very large from the original one.
How can I convert it into byte array with the same size or nearly the same size as the original JPEG?
Therefore, I wonder if the inverse conversion will convert byte array to jpeg the same size or not ?

Here is my code:

    Resources r = this.getResources();
    Bitmap bm  = BitmapFactory.decodeResource(r,R.drawable.plot);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bm.compress(Bitmap.CompressFormat.JPEG,100,baos);
    byte[] byteArray = baos.toByteArray(); 
How to solve:

bitmap.compress has a property of quality (the 2nd one). try reducing if from 100 to a lower number (0-100).

###

The JPEG you loaded is most likely to have a level of compression, which is what makes JPEGs smaller, by trading quality for size.

In your code you are setting a compression level of 100, this means no compression at all, so the bitmap is saved in JPEG format, but as it is without any size/quality reduction at all.

If you change the compression level to anything lower than 100 you will see how the file size gets smaller. Try between 80 to 90 to keep a good quality while getting a smaller file.

###

How can I convert it into byte array with the same size or nearly the same size as the original JPEG?

Just load the jpg file in a byte array if you need it in a byte array.

There is no need to convert to bitmap first.

Leave a Reply

Your email address will not be published. Required fields are marked *