Java conversion of images to byte array sizes

I have the following code snippet to convert an image to a byte array.

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

The problem I am facing is that the image size is about 2.65 MB. However, imageBytes.length gives me a value of more than 5.5 MB. Can anyone tell me where I am going wrong?

+6
source share
2 answers

PNG is not always the right round-trip format. Its compression algorithm can give different results.

EDIT: The same goes for JPEG.

+4
source

I used the code below to fix the problem.

 FileInputStream fis = new FileInputStream(inputFile); ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte[] buf = new byte[1024]; try { for (int readNum; (readNum = fis.read(buf)) != -1;) { bos.write(buf, 0, readNum); } } catch (Exception ex) { } byte[] imageBytes = bos.toByteArray(); 

Courtesy: http://www.programcreek.com/downloads/convert-image-to-byte.txt It seems to work fine. Please let me know if any of you see any problems with this approach.

+2
source

Source: https://habr.com/ru/post/906394/


All Articles