Why Java ImageIO flattens JPEG colors

ketorin picture ketorin · Aug 13, 2009 · Viewed 7k times · Source

When I read certain JPG files, colors are flattened. Here is a simple example that reads a jpg and just writes the same image to another file.

import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;

public class JPegReadTest {
    public static void main(String[] args) {
        if (args.length == 2) {
            try {
                BufferedImage src = ImageIO.read(new File(args[0]));
                ImageIO.write(src, "jpg", new File(args[1]));
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            System.err.println("Usage: java JPegReadTest src dest");
        }
    }
}

If you try this with for example http://www.flickr.com/photos/visualpanic/233508614/sizes/l/ , the colors of the destination image differ from the source file. Why is that? How to fix it?

Also tried saving the image as png, but the colors are bland in it too (so assuming color info is not read properly).

Answer

erjiang picture erjiang · Aug 13, 2009

It could be several reasons.

  1. JPEG color data is often stored as YCrCb instead of RGB, although conversions should be mostly unnoticeable.
  2. JPEG often has an embedded color profile, but many applications do not understand this and simply ignore it (in which case, your output file might be missing the color profile).
  3. Gamma value could be reset or missing after Java mangles it.

I didn't actually try your example... could you please post both before and after files? Without actually being able to examine the result file, it's hard to tell if this extra data is there or not.

Edit: Yeah, it's clear that your original and converted images have different color profiles. Java stripped out the original's color profile and used generic sRGB instead. They look the same to us on Windows with Firefox and assorted programs because these programs don't use the color profile when renderer. However, on your Mac, Mac actually supports these color profiles (cue debate over Macs for graphics, etc.) and so they render differently. I don't have a Mac handy, but I suspect that if you open the files in Photoshop on any platform, you'll see the difference.