简体   繁体   中英

Exception in thread "main" java.lang.IllegalArgumentException: Width (0) and height (0) must be non-zero

`

immagineRegistrati = new ImageIcon("../img/registrati.png");
scalaRegistrati = new ImageIcon(immagineRegistrati.getImage().getScaledInstance(immagineRegistrati.getIconWidth()/20*2, immagineRegistrati.getIconHeight()/20*2, java.awt.Image.SCALE_SMOOTH)); //immagine in scala
        

`

This is the line of code that give me the error of the title. Anyone have any idea?

ImageIcon can return before the image is fully loaded (it's loaded in the background), this will mean that it's possible for the width and height to be zero

One solution would be to use a MediaTracker , this will allow you to "wait" till the image is fully loaded, for example.

try {
    MediaTracker mt = new MediaTracker(new JPanel());
    Image image = new ImageIcon().getImage();
    mt.addImage(image, 0);
    System.out.println("Wait for...");
    mt.waitForAll();
    System.out.println("I be loaded");
    // Image is now fully loaded, you should be able to deal with it
} catch (InterruptedException ex) {
    ex.printStackTrace();
}

Having said that, an overall better solution would be to use ImageIO.read to load the image. Not only does it load the image before returning, it will throw an Exception if the image can't be loaded for some reason (something ImageIcon doesn't do)

"Oh GOD SPIDERS" is also correct, you could have scaled the image into oblivion, so you might want to check that your target size isn't zero before trying to scale the image.

See Reading/Loading an Image for more details

I would also suggest avoiding getScaledInstance , it tends to not be very good.

I tend to use a "divide and conquer" approach (dividing the image by half till I reach the desired size), for example and example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM