如何从java包中加载图像

如何从java包中加载图像,java,Java,我通常用这个从同一个包中加载 Image image; String img = "image.png"; ImageIcon i = new ImageIcon(this.getClass().getResource(img)); image = i.getImage(); 如何从为图像指定的包中加载图像?您可以尝试任何一种 // Read from same package ImageIO.read(getClass().getResourceAsStream("c.png")); /

我通常用这个从同一个包中加载

Image image;
String img = "image.png";
ImageIcon i = new ImageIcon(this.getClass().getResource(img));
image = i.getImage();
如何从为图像指定的包中加载图像?

您可以尝试任何一种

// 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"));
使用

ImageIcon图标=新的ImageIcon(

建议“image.png”与this

您可以使用绝对路径引用驻留在不同包中的资源

String img = "/path/to/images/image.png";
ImageIcon i = new ImageIcon(this.getClass().getResource(img));
这里的重要概念是理解路径的后缀是类路径

就个人而言,您应该在
ImageIcon
上使用
ImageIO
,除了支持更多格式之外,当出现问题时,它还会抛出
IOException
,并保证返回完全加载的图像(成功时)

有关不需要在本地使用(如“this”)的更多详细信息,请参见:
this.getClass().getResource(img);
只需全局使用类加载器:
ClassLoader.getSystemResource(path);
我将在下面向您展示我的库函数

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; }
    }
}

如果您的
img.png
在包
pack
中,请使用
PackageResourceLoader.loadImageIcon(“pack/img.png”)

那么,相对于类,图像在哪里?请提供更多上下文,它应该很容易帮助您。在这里找到解决方案,谢谢我以前看过,但没有人解释过您的项目结构是什么?
String img = "/path/to/images/image.png";
ImageIcon i = new ImageIcon(this.getClass().getResource(img));
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; }
    }
}