8

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

Community
  • 1
  • 1

2 Answers2

8

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.

Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045
  • 1
    See also [`createCompatibleImage()`](http://docs.oracle.com/javase/6/docs/api/java/awt/GraphicsConfiguration.html). – trashgod Aug 20 '12 at 18:46
5

It looks like you have found a bug in ImageIO.read... (I can reproduce the red tint, and it is definitely not how it should look like).

You can try to

  • save the JPEG files with other settings
  • open/re-save the file with other programs (hoping to get a more common JPEG-encoding)
  • or use the Toolkit method (if you don't control the images).

The only problem with the Toolkit method is that the getImage() method returns immediately after it is invoked and the loading is happening on a background thread, so you cannot start working with the Image object immediately.

lbalazscs
  • 17,474
  • 7
  • 42
  • 50