I am having trouble reading an image. If I do the following
URL url = new URL("http://tctechcrunch2011.files.wordpress.com/2012/10/gmm.jpg");
ImageInputStream stream = ImageIO.createImageInputStream(url.openStream());
ImageReader reader = ImageIO.getImageReaders(stream).next();
reader.setInput(stream, true, true);
BufferedImage image = reader.read(0);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ImageWriter writer = ImageIO.getImageWritersByFormatName("JPEG").next();
ImageOutputStream ios = ImageIO.createImageOutputStream(bos);
writer.setOutput(ios);
IIOImage ioImage = new IIOImage(image, null, null);
writer.write(ioImage);
ios.close();
FileOutputStream fos = new FileOutputStream("badimage.jpeg");
fos.write(bos.toByteArray());
fos.close();
the image is written with a red tint. Is there some option that needs to be set to read this image correctly?
The problem maybe related to ImageIO.read that fails to correctly read some JPG images. Here is a similar bug (Bug ID: 4881314) that may still be partially unresolved.
As an alternative you can try using Toolkit.createImage that seems to handle the specified image correctly. For example:
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
class TestImage {
public static void main(String args[]) {
try {
URL imageUrl = new URL(
"http://tctechcrunch2011.files.wordpress.com/2012/10/gmm.jpg");
BufferedImage ioImage = ImageIO.read(imageUrl);
Image toolkitImage = Toolkit.getDefaultToolkit().createImage(
imageUrl);
JPanel panel = new JPanel();
panel.add(new JLabel(new ImageIcon(ioImage)));
panel.add(new JLabel(new ImageIcon(toolkitImage)));
JOptionPane.showMessageDialog(null, panel, "ImageIO vs Toolkit",
JOptionPane.INFORMATION_MESSAGE);
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage(), "Failure",
JOptionPane.ERROR_MESSAGE);
e.printStackTrace();
}
}
}
Here is the result:

Sorry. I don't have the answer to why there is a red tint.
This is how we read images in our software. In our case we are using the scalar library to resize the image.
URL url = new URL("http://tctechcrunch2011.files.wordpress.com/2012/10/gmm.jpg");
BufferedImage source = javax.imageio.ImageIO.read(url);
BufferedImage manipulated = ...
FileOutputStream fos = new FileOutputStream("badimage.jpeg");
javax.imageio.ImageIO.write(manipulated , "png", fos);
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