6

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?

7
  • 1
    How do you know that the size is around 2.65MB? Can you open the resulting bytes? Does it look okay? Commented Jan 19, 2012 at 12:57
  • 1
    Are you sure the input image really is in PNG format? Commented Jan 19, 2012 at 12:58
  • @Thilo - The image is an uploaded image from my local machine. I checked the file both on my local machine and on the server. It has a size of 2.65MB. I am using BufferedImage image = ImageIO.read(inputFile); to create the image object from the file. Yes, the byte[] stored looks OK except for the size. Commented Jan 19, 2012 at 13:08
  • If you have the uploaded PNG image file, why don't you just use that one? If on the other hand, you manipulate the image, the result could compress differently (much differently apparently, maybe there are some settings to play with). Commented Jan 19, 2012 at 13:10
  • Both of you were right. The uploaded image was in jpg format, so changed the code to use "jpg" and "png" based on the file type accordingly. However, the size now shows 0.5MB now, which is way lower than the actual size. I'm pretty sure I am losing the quality of the image. The reason that I am having to do this is because I need to store the image on the Amazon S3 server which accepts the data only in byte[] format. Do you guys see any solution? Commented Jan 19, 2012 at 13:15

2 Answers 2

4

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

EDIT: Same applies to JPEG.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.