ricky3350
ricky3350

Reputation: 1738

Using ImageIO.read gives a modified image

I was doing some stuff with images in JLabels, and I noticed that a few of the images (ones that contained black) that I was using were brighter in the label than they were supposed to be. The images were loaded through ImageIO#read(File). Images loaded through ImageIcon constructors alone look normal.

Here's a small test that I threw together for this image:

Test image

JFrame frame = new JFrame();
frame.setLayout(new FlowLayout());
frame.setSize(320, 320);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

URL imageURL = new URL("https://wiki.factorio.com/images/Crude-oil.png");

frame.add(new JLabel(new ImageIcon(ImageIO.read(imageURL))));

frame.add(new JLabel(new ImageIcon(imageURL)));

frame.setVisible(true);

The result:

Result

Any ideas as to why this might be happening?

Upvotes: 1

Views: 253

Answers (1)

Manoj Khanna
Manoj Khanna

Reputation: 63

This is a known bug and it occurs when ImageIO.read() fails to find the proper color model of an image.

On the contrary, the constructor ImageIcon(Url) displays the image properly as it retrieves the image using Toolkit.getDefaultToolkit().getImage(Url).

This bug can occur on other image extensions too. See this.

EDIT

Scroll down and compare the Color Type in the PNG section from the links below.

http://regex.info/exif.cgi?imgurl=https://wiki.factorio.com/images/Crude-oil.png

http://regex.info/exif.cgi?imgurl=http://www.sherv.net/cm/emoticons/hand-gestures/victory-fingers-black-smiley-emoticon.png

You will see that both the color types are different besides both images being PNGs. The problem with ImageIO.read() is that it can read RGB with Alpha properly but not Grayscale with Alpha.

I also found that ImageIO.read().getType() returns 0 = TYPE_CUSTOM for the first image and 6 = TYPE_4BYTE_ABGR for the second. TYPE_CUSTOM is usually returned for images whose type is not recognized.

Upvotes: 2

Related Questions