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

I am creating a user interface using Swing and I want to display the image in JLabel . The code I use is as follows:

  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 (just some of them), I get a red image (different than the one I see in Paint.NET). I used this image: img.jpg

So I tried (as an alternative):

 Toolkit.getDefaultToolkit().createImage(new File("img.jpg").getAbsolutePath()); 
  • Does anyone have an idea why this is happening? Is this a special JPEG that is not supported?
  • I read on this forum that most people recommend using ImageIO ( here ). Why?

thanks a lot

+6
source share
2 answers

As discussed here , your JPEG image may contain false transparency information. One simple way is to make an image in a buffer having a compatible color model, as shown here.

+7
source

Looks like you found an error in ImageIO.read ... (I can reproduce a red tint, and that is definitely not what it should look like).

You may try

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

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

+5
source

Source: https://habr.com/ru/post/923301/


All Articles