Search code examples
javaswingimageicon

Java swing Image always has height and width of -1


I know that the method returns -1 when it couldn't get the width or height of the image, but I hope you can tell me why it can't manage to do that. Here I create a few ImageIcons and save them in an Image Array:

for(int x = 0; x < playerSprites.length; x++){
    playerSprites [x] = new ImageIcon("player" + x + ".png").getImage()
}

Later I create an instance of the class which only creates this Array at the moment. When I then want to get the images from the Array in the other class I check their height and width and I always get -1 on both:

public Image nextImage(String name){
    Image image = null;
    if(name.equals("player")){
        if(counter == animationImageManager.getPlayerSprites().length-1){
            counter = 0;
        }
        image = animationImageManager.getPlayerSprites()[counter];
        counter++;
    }
    return image;
}

Solution

  • If image is not found then still it return -1 for height and width.

    Try below sample code to reproduce the issue:

    System.out.println(new ImageIcon("").getImage().getWidth(null)); // print -1
    

    It's worth reading Java Tutorial on Loading Images Using getResource


    May be it's not loading the images properly.

    You can try any one based on image location.

    // Read from same package 
    ImageIO.read(getClass().getResourceAsStream("c.png"));
    
    // Read from images folder parallel to src in your project
    ImageIO.read(new File("images/c.jpg"));
    
    // Read from src/images folder
    ImageIO.read(getClass().getResource("/images/c.png"))
    
    // Read from src/images folder
    ImageIO.read(getClass().getResourceAsStream("/images/c.png"))
    

    Read more...