Toolkit.getDefaultToolkit().createImage() vs ImageIO.read()

user1612150 picture user1612150 · Aug 20, 2012 · Viewed 8k times · Source

I'm creating a UI using Swing and I want to display an image in a JLabel. The code I use is the following:

 JLabel label = new JLabel(new ImageIcon(ImageIO.read(new File("img.jpg"))));

This works fine if I use png images but when it comes to jpg (only some of them), I get a redish image (a different one than the one I see in Paint.NET). The image I used is this one: img.jpg

So I tried (as an alternative):

Toolkit.getDefaultToolkit().createImage(new File("img.jpg").getAbsolutePath());
  1. Does anyone have an idea of why this happening? Is it a special JPEG format which is not supported?
  2. I've read on this forum that most people recommend to use ImageIO (here for example). Why?

Thanks a lot

Answer

trashgod picture trashgod · Aug 20, 2012

As discussed here, your JPEG image may contain spurious transparency information. One simple expedient is to render the image in a buffer having a compatible color model, as shown here.