简体   繁体   中英

getResource, image width returns -1

I have the following snippet that loads the images:

    String imgName = "/assets/" + name;
    URL imgURL = Groovy.class.getResource(imgName);
            System.out.println(imgURL.getPath());
    Toolkit tk = Toolkit.getDefaultToolkit();
    Image image = tk.getImage(imgURL);
    return image;

And where the image is drawn:

        Graphics2D g = (Graphics2D) strategy.getDrawGraphics();
        g.setColor(Color.black);
        g.fillRect(0,0,screenWidth,screenHeight);
        g.drawImage(background, 0, 0, null);
        System.out.println(background.getWidth(null));
        if (background.getWidth(null) < 0)
            System.exit(1);

However imgURL always returns null. I'm using Eclipse (and fresh to it, blegh), and running the classes with run or debug option. If I change the path, it gives a file not found exception.

File structure is as followed:

Project -> src and assets -> src has Groovy, assets has image -> Groovy has Groovy.class

Edit: I switched back to Netbeans. The imgURL is now loading fine and getPath returns it's correct path. However the image width / height return -1. This is the actual problem now.

Edit: -1 means that the width is not yet known, however displaying the image shows a white screen.

Javadoc to the rescue:

Before delegation, an absolute resource name is constructed from the given resource name using this algorithm:

If the name begins with a '/' ('\/'), then the absolute name of the resource is the portion of the name following the '/'. Otherwise, the absolute name is of the following form:

  modified_package_name/name 

Where the modified_package_name is the package name of this object with '/' substituted > for '.' ('\.').

In short: relative paths can't use .. to go a level up. Use an absolute name (starting with a / , from the root of the classpath).

Moreover, getResource loads resources from the classpath. If the image is not in the classpath, it won't work. Your file tree is not clear at all, but it seems that you haven't understood what the classpath is. If you want to load a file from the file system, use File IO, not resources.

The problem resided in the use the toolkit to get the image, possibly because I'm using OpenJDK? Anyway, using ImageIO.read(imgURL) fixed this.

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