Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java convert image to byte array size issues

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?

like image 517
sure_render Avatar asked Jan 19 '12 12:01

sure_render


2 Answers

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

EDIT: Same applies to JPEG.

like image 168
Funky coder Avatar answered Oct 14 '22 10:10

Funky coder


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.

like image 2
sure_render Avatar answered Oct 14 '22 10:10

sure_render