views:

1375

answers:

2

I want compress jpeg files using Java. I do it like this:

  1. Read the image as BufferedImage
  2. Write the image to another file with compression rate.

OK, that seems easy, but I find the ICC color profile and the EXIF information are gone in the new file and the DPI of the image is dropped from 240 to 72. It looks different from the origin image. I use a tool like preview in OS X. It can perfectly change the quality of the image without affecting other information.

Can I done this in Java? At least keep the ICC color profile and let the image color look the same as the origin photo?

+1  A: 

See the Compressing a JPEG File example in the Java Developer's Almanac using an ImageOutputStream. You'll have to experiment with the compression quality in the ImageWriteParam parameter.

Bill the Lizard
I think he wants a way to keep the metadata in the JPEG to be preserved rather than trying to preserve the image quality.
coobird
I don't quite know java imageio. But the "Compressing a JPEG File example" isn't useful to me. 1. It lost all the exif and other information in the jpge2. It drop the image dpi from 240 to 723. It makes my out image pale (My images to be compressed are come from the digital camera, big and high definition, I tried this method on small jpgs, it works great, but on my images, all the image compressed is pale than the origin)Is the problem of java? Or there is some magic spell in there?
guitarpoet
A: 

Finally find a way to do this.

Use javax.imageio.IIOImage. It can be readed by JpegImageReader.

But there was a bug in it, a bug last for 6 years. :(

http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4924909

Luckily, if you do some hack(Fake the JFIF section), and it works. :D

So, this problem can be solved like this:

  1. Use ImageIO to get the ImageReader for jpeg
  2. Read the jpeg image into a memory buffer
  3. If it fails at bug 4924909 then fix the image buffer with a fake JFIF information
  4. Use ImageWriter to write the file, let the ImageWriterParam to do the trick.

Well, it seems to be ok(Every information saved), except for one thing, the output image is brighter(or rather say, pale) than the original image(It won't happen when I use preview of OS X to compressed photo, so the problem must be in my code or java, or my wrong usage :( ).

So, my problem for compressing jpeg in java is not solved yet.

Any suggestions?

guitarpoet
Fine, I give up. ImageIO can't work well(at least for me). I just want change the quality of the image to compress it without lose any information and looks as same as possible with the origin photo.Java failed me, I'm going to use ImageMagic and JNI to do this.Maybe I was wrong. Anyone from oracle can help?
guitarpoet