繁体   English   中英

Java ImageIO.read(URL)不应返回null

[英]Java ImageIO.read(URL) returning null when it shouldn't

好的,所以我花了大约15个小时来解决这个问题。 我正在将此程序导出到不可运行的jar文件中。 问题是我试图将图像加载到jar中并将其设置为变量。

我看过其他帖子,我想我已经尽力找到了所有可以找到的东西,但似乎没有任何效果。

我不是在问如何查找图像,因为我可以获得图像的URL,但是ImageIO.read(URL)不会引发任何异常,而是返回null。 该图像是我听说过的.png与ImageIO.read()兼容。 我正在使用一个API,所以log()行是什么。

任何帮助表示赞赏。 谢谢!

我的项目:

    Project
    ->src
    -->package
    --->Main.java
    --->paint.png

我的代码:

在我的主要方法中:(mainPaint是私有图像)

    mainPaint = getImage("paint.png");

方法:

private Image getImage(String fileName) {

    URL url = getClass().getResource(fileName);
    BufferedImage image = null;

    log(url.toString()); // To make sure I have the correct file
    // returning jar:file:/C:/Users/Me/MyJar.jar!/package/paint.png

    try {
        image = ImageIO.read(url);
    } catch (IOException e1) {
        log("Error converting url to image.");
        // This is not happening
    }

    if (image == null) {
        log("Image is null.");
        // This is happening
    }

    return image;
}

网址无效吗? 我只是想念什么吗? 我只是想将本地图像保存在jar中作为Image对象,我觉得这对我想做的事情来说太困难了。

编辑:我也只是试图使mainPaint一个BufferedImage并使用:

    Image image = Toolkit.getDefaultToolkit().getImage(getClass().getResource(fileName));
    if(image == null) {
        log("Image is null");
    }
    log("Height: " + image.getHeight(null));
    log("Width: " + image.getWidth(null));

    BufferedImage bimage = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_ARGB);

    // Draw the image on to the buffered image
    Graphics2D bGr = bimage.createGraphics();
    bGr.drawImage(image, 0, 0, null);
    bGr.dispose();

    // Return the buffered image
    return bimage;

图片的高度和宽度返回-1?

ImageIO.read()将仅加载GIF,PNG,JPEG,BMP和WBMP图像类型。 任何其他图像类型都将返回null且没有错误。

它可以回答您的问题。

ImageIO.read()将不会加载SVG文件,因此,如果您的图像位于SVG formate中,则需要向其添加插件以支持SVG

是另一篇SO帖子,解释了在哪里可以做到这一点。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM