从.jar文件加载Java映像 [英] Java Image Loading from .jar File

查看:67
本文介绍了从.jar文件加载Java映像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从名为Custom的文件夹中加载图像,用户将其放入其中.这是我用来加载图像的方法:

I'm trying to load an image from a folder named Custom that the user places images into. Here is the method I used to load images:

public BufferedImage getCustImg(String path){
    BufferedImage img = null;
    String s = get.getProgramPath();
    path = path.trim();
    String s2 = s + "\\Custom\\" + path + ".png";

    try{
        img = ImageIO.read(this.getClass().getResource(s2));//gets image from file path
    } catch (IOException e) {
        e.printStackTrace();
    }
    return img;
}

这是程序路径方法

public String getProgramPath(){
    File f = new File("./Resources/Sprtes/blank.png");
    String s = f.getAbsolutePath();
    String[] stringArr = s.split("Resources");
    String s2 = stringArr[0];
    s2 = s2.substring(0, s2.length() - 3);
    return s2;
}

当我运行代码时,一切正常,但是当我尝试将程序作为.jar文件运行时,出现了问题.当我使用.jar文件运行该文件时,不会加载该图像.这是自定义文件夹与.jar文件相关的位置:

When I run the code everything works fine but the issue appears when I try to run the program as a .jar file. When I run it using a .jar file, the image doesn't load. This is where the custom folder is in relation to the .jar file:

文件结构

我应该如何更改方法以确保其有效?

How should I change the method to make sure that this works?

推荐答案

因此,感谢Luke Lee和Olithegoalie,我找出了问题所在,

So I figured out the problem thanks to Luke Lee and Olithegoalie,

img = ImageIO.read(this.getClass().getResource(s2));如果路径超出了jar的范围,则无法使用,因此我不得不将其更改为

img = ImageIO.read(this.getClass().getResource(s2)); Doesn't work if the path goes outside the jar so I had to change it to

public BufferedImage getCustImg(String path){
    BufferedImage img = null;
    String s = get.getProgramPath();
    path = path.trim();
    String s2 = s + "\\Custom\\" + path + ".png";
    try{
        img = ImageIO.read(new File(s2));
    } catch (IOException e) {
        e.printStackTrace();
    }
    return img;
}

这篇关于从.jar文件加载Java映像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆