1

I am trying to insert a 1 MB image inside neo4j using the following code:

 File fnew = new File("C:\\Users\\myimage.jpg");
 BufferedImage originalImage = ImageIO.read(fnew);
 ByteArrayOutputStream baos = new ByteArrayOutputStream();
 baos.flus();
 ImageIO.write(originalImage, "jpg", baos);
 return baos.toByteArray();

Then I insert this byte array using:

 user.setProperty("photo", photo);

This all goes fine. When I try to select the photo, using the following method, it writes it on my hard drive disk as 536KB instead of the 1 MB original size.

 byte[] imageInByte = (byte[]) user.getProperty("photo");
 InputStream in = new ByteArrayInputStream(imageInByte);
 BufferedImage bImageFromConvert = ImageIO.read(in);
 ImageIO.write(bImageFromConvert, "jpg", new File("C:\\newimage.jpg"));

Now the weird part: I can see the image, open it, same resolution, I don't see any difference in terms of quality though. Looks like it is compressed.

Why is this happening?

Moody
  • 851
  • 2
  • 9
  • 23

1 Answers1

3

Saving a jpg image through ImageIO results in lossy compression of the jpg (I believe the quality defaults to 70%). You can a) Change the the quality of the image when you write to file (see Setting jpg compression level with ImageIO in Java ) or b) if you don't actually need the BufferedImage, just read/write the bytes from file to database.

Community
  • 1
  • 1
copeg
  • 8,290
  • 19
  • 28
  • 1
    +1 for explaining why it is happening. Yet it might be worth mentioning that there is no need to use ImageIO if one is not processing the image. Read the bytes from the file directly –  Apr 02 '15 at 20:51
  • Thanks! That was indeed the problem! I don't use the BufferedImage anymore. – Moody Apr 02 '15 at 21:17