Fra*_*ner 6 java bufferedimage javax.imageio
保存此图片时:

用这种方法:
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();
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的结果:

但是,所有图片都不会发生这种情况.
你能告诉我为什么吗?
根据@ uckelman 对这篇文章的评论,当图像缺少JFIF头时,Java的解码器对图像格式的假设与大多数其他渲染不同:
我相信你在这里和这里找到了关于如何检测坏JPEG的问题的答案.你有一个没有JFIF标记的JPEG.在这种情况下,所有其他图像加载器都假设数据是YCbCr,但ImageIO除外,它假定当通道1和2未进行二次采样时它是RGB.因此,检查前4个字节是否为FF D8 FF E1,如果是,则检查通道1和2是否进行二次采样.这就是你需要转换的情况.