Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Image changes color when saved with java [duplicate]

When I save this image:

Holiday Doodle

with this method:

private final static Path ROOT_PATH = Paths.getPath("C:/images");

private static void saveImageFromWebSimple(final String url) {
    URL u = null;
    try {
        u = new URL(url);
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    String file = url.substring(url.indexOf("//") + 2);
    Path filePath = ROOT_PATH.resolve(file);
    try {
        Files.createDirectories(filePath.getParent());
        BufferedImage img = ImageIO.read(u);
        ImageIO.write(img, "jpg", filePath.toFile());
    } catch (IOException e) {
        e.printStackTrace();
    }
}

this is my result:

Result

This doesn't happen with all pictures though.

Can you tell me why?

like image 629
Franz Ebner Avatar asked Dec 26 '13 17:12

Franz Ebner


1 Answers

According to @uckelman's comment on this post, Java's decoder makes a different assumption about the format of the image than most other renders when the image is missing the JFIF header:

I believe the answer to your question of how to detect the bad JPEGs is found here and here. What you have is a JPEG with no JFIF marker. All other image loaders assume that the data is YCbCr in that case, except for ImageIO, which assumes that it is RGB when channels 1 and 2 are not subsampled. So, check whether the first 4 bytes are FF D8 FF E1, and if so, whether channels 1 and 2 are subsampled. That's the case where you need to convert.

like image 174
antiduh Avatar answered Oct 15 '22 13:10

antiduh