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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With