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?
PNG is not always a faithful round-trip format. Its compression alghoritm can yield different results.
EDIT: Same applies to JPEG.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With