简体   繁体   中英

How to load Images from a package in java

I usually use this to load from the same package

Image image;
String img = "image.png";
ImageIcon i = new ImageIcon(this.getClass().getResource(img));
image = i.getImage();

How can I load an image from a package specified for images?

You can try any one

// Read from same package 
ImageIO.read(getClass().getResourceAsStream("c.png"));

// Read from absolute path
ImageIO.read(new File("E:\\SOFTWARE\\TrainPIS\\res\\drawable\\c.png"));

// Read from images folder parallel to src in your project
ImageIO.read(new File("images\\c.jpg"));

Use

ImageIcon icon=new ImageIcon(<any one from above>);

You can use BufferedImage also in place of ImageIcon directly.

For more information read it here How to retrieve image from project folder?

Image image;
String img = "image.png";
ImageIcon i = new ImageIcon(this.getClass().getResource(img));
image = i.getImage();

Suggests that "image.png" resides within the same package as the class represented by this

You can use absolute paths to reference resources that reside within different packages

String img = "/path/to/images/image.png";
ImageIcon i = new ImageIcon(this.getClass().getResource(img));

The important concept here is to understand that the path is suffixed to class path

Personally, you should be using ImageIO over ImageIcon , apart from supporting more formats, it throws an IOException when something goes wrong and is guaranteed to return a fully loaded image (when successful).

SeeHow to read images for more details

You don't need to use(like "this") locally: this.getClass().getResource( img ); Just use class loader globally : ClassLoader.getSystemResource( path ); I'm gonna show you my library function below

public final class PackageResourceLoader {

    // load image icon
    public static final ImageIcon loadImageIcon( final String path ) {

        final URL res = ClassLoader.getSystemResource( path );

        return new ImageIcon( res );
    }


    // load buffered image
    public static final BufferedImage loadBufferedImage( final String path ) {

        final URL res = ClassLoader.getSystemResource( path );

        try { return ImageIO.read( res ); }
        catch( final Exception ex ) { return null; }
    }
}

if your img.png is in package pack use PackageResourceLoader.loadImageIcon( "pack/img.png" );

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