Java convert image to byte array size issues

可紊 提交于 2019-12-10 13:22:12

问题


I have the below piece of code to convert an image to byte array.

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

The issue that I am facing is that the size of the image is around 2.65MB. However, imageBytes.length is giving me a value more than 5.5MB. Can somebody let me know where I am going wrong?


回答1:


PNG is not always a faithful round-trip format. Its compression alghoritm can yield different results.

EDIT: Same applies to JPEG.




回答2:


I used the below code 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 be working fine. Please let me know if any of you see any issues in this approach.



来源:https://stackoverflow.com/questions/8926348/java-convert-image-to-byte-array-size-issues

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!