Image changes color when saved with java [duplicate]

孤者浪人 提交于 2019-11-30 15:26:39

问题


When I save this image:

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:

This doesn't happen with all pictures though.

Can you tell me why?


回答1:


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.



来源:https://stackoverflow.com/questions/20789043/image-changes-color-when-saved-with-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!