Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Java ImageIO flattens JPEG colors

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).

like image 500
ketorin Avatar asked Aug 13 '09 12:08

ketorin


2 Answers

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.

like image 76
erjiang Avatar answered Nov 05 '22 21:11

erjiang


Perhaps your source image has an assigned color profile with a gamut wider than sRGB (like Adobe RGB), and your load/save cycle isn't preserving the colorspace information? With no color profile, your viewer will assume sRGB, and the compressed gamut will make everything look "blah". If you have exiftool,

exiftool -ProfileDescription filename.jpg

is a quick way to verify the color profiles on your source and output images.

like image 41
hobbs Avatar answered Nov 05 '22 20:11

hobbs