【问题标题】:Images won't load from jar file [duplicate]图像不会从 jar 文件中加载 [重复]
【发布时间】:2013-06-15 20:54:19
【问题描述】:

我已经尝试过搜索,但仍然没有找到解决方案。当我导出到 jar 文件时,我的所有图像突然不再工作了。它们在 Eclipse 中运行良好,我确保它们在 jar 文件中。我尝试使用获取资源方法并使图像加载器类自动上升到目录树,但它仍然失败。这是我所做的:

public static Image load(String path)
{   String temp = path;
    Image image = null;
    try {

     image = new ImageIcon(path).getImage();


    } 

    catch ( Exception e )
    {   
        try {
         while (image == null )
         {
              image = new ImageIcon("../"+ path).getImage();
         }
         if ( path.equals("../../../../../../"+ temp))
         {
             while ( image ==null)
             {
                 image = new ImageIcon("./"+ path).getImage();
             }
         }
        }
        catch ( Exception ae)
        {


        System.err.println("cannot locate image");
    }} 


    return image;
}   

我将发送它的路径如下:“doc/icon.png”

我已经把我所有的图片都放在了doc文件夹中,结构是final Project,里面是doc文件夹,然后是src文件夹,里面包含了所有的包。

【问题讨论】:

  • 打印路径看看是否正确
  • if ( path.equals("../../../../../../"+ temp)) 是什么意思?
  • 部署时,这些资源可能会变成embedded-resource。在这种情况下,资源必须由URL 而不是File 访问。查看标签的info page,了解形成URL的方法。

标签: java image jar


【解决方案1】:

试试这个:

Image.class.getClassLoader().getResource("/filepath/filename").getFile()

【讨论】:

  • 公平 -> 更新了答案
【解决方案2】:

图像路径尝试找出您尝试从中加载图像的路径,而不是“蛮力”。您可以通过以下方式进行查找

System.out.println("Path: " + (this.getClass().getClassLoader().getResource("")).getPath());

然后尝试像这样或像@Balint Bako allready sed 那样加载它。

Image img;
URL url = new File("the path you found out").toURI().toURL();
BufferedImage img = ImageIO.read(url);

【讨论】:

    猜你喜欢
    • 2011-06-08
    • 1970-01-01
    • 1970-01-01
    • 2021-08-06
    • 2011-07-18
    • 2013-08-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多