问题
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