sure_render
sure_render

Reputation: 148

Convert BufferedImage to byte[] without losing quality and increasing size

I am trying to convert a BufferedImage to a byte array. I have two conditions. 1. I should not lose the quality of the image. 2. The size of the byte array should be the same as the actual image. I tried a couple of options.

Option 1:

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(image, "png", baos);
        baos.flush();
        byte[] imageBytes = baos.toByteArray();
        baos.close();

Option 2:

        WritableRaster raster = image.getRaster();
        DataBufferByte data   = (DataBufferByte) raster.getDataBuffer();
        byte[] imageBytes = data.getData();

Both these options increase the size of the image (more than twofold for large images).

Appreciate any help. Thanks!

Upvotes: 1

Views: 8242

Answers (1)

ziesemer
ziesemer

Reputation: 28687

The PNG format uses lossless data compression, so you shouldn't need to worry about loosing the quality of the image with your option 1.

How are you seeing an increase in the size of the image? I'm sure you know what imageBytes.length is. What are you comparing this to that you're thinking this is twice as large as it should be? (I'm thinking your assumption may be incorrect.)

It is possible that your original source file is just using a higher compression setting than Java is re-compressing it with. You may need to pass some additional parameters into your writer. See how to compress a PNG image using Java for some additional details - specifically the link to http://www.exampledepot.com/egs/javax.imageio/JpegWrite.html.

Upvotes: 2

Related Questions