【问题标题】:ImageIO.read returns NULL, with no errorsImageIO.read 返回 NULL,没有错误
【发布时间】:2012-04-14 04:43:34
【问题描述】:

以下代码似乎无法正常工作,即使该文件似乎可以找到。

    images = new BufferedImage[32];
    FileInputStream fis = null;
    for (int i = 0; i < 32; i++) {
        File file = new File("tiles\\"+i+".bmp");
        if (!file.exists()){
            System.out.println("File  "+i+" failed");
        }
        try { 
            fis = new FileInputStream(file); 
        } catch (FileNotFoundException e) { 
            System.err.println(e + "" + i); 
        }
        try { 
            images[i] = ImageIO.read(fis); 
        } catch (IOException e) { 
            System.err.println(e + "" + i); 
        }
        if (images[i] == null) {
            System.out.println("Image "+i+" failed");
        }
    }

提前感谢您的帮助。

编辑:结果是我尝试 Graphics.drawImage(images[0]);,它给了我一个空指针异常。这段代码在这里完成得很好。

Edit: Changed 按照建议移动了 if(!file.exists()),并将文件包装在输入流中。

【问题讨论】:

  • 你能描述一下结果吗?一个疯狂的猜测:路径不正确...
  • 为什么不进行测试 if (!file.exists()) System.out.println("File "+i+" failed");在阅读之前?

标签: java image


【解决方案1】:

ImageIO.read(*...) 只会加载这些图像类型 GIFPNGJPEGBMP 和 WBMP。

任何其他图像类型都将返回 null 而不会出错。

参考: http://docs.oracle.com/javase/tutorial/2d/images/loadimage.html

我确实意识到这不是对特定原始问题的解决方案,而是对所提出问题的解决方案。

【讨论】:

    【解决方案2】:
    如果未找到已注册的 ImageReader

    ImageIO.read(file); 将返回 null。请检查您是否注册了任何ImageReader

    我认为这段代码 sn-p 可以帮助你

    File file = new File("bear.jpg"); // I have bear.jpg in my working directory  
        FileInputStream fis = new FileInputStream(file);  
        BufferedImage image = ImageIO.read(fis); //reading the image file  
    

    您只需将文件包装到 FileInputStream 中,然后将其传递给 read()

    【讨论】:

    • 我可能仍然没有正确执行此操作,但我所做的事情并不成功。我更改了上面的代码以显示更改的内容。
    • 你能说一下你磁盘中的图片文件名是什么吗?
    • @Naberius 你能说一下磁盘中的图像文件名是什么吗?它在我的情况下非常有效。
    • 抱歉,周末不能上网。这些文件被命名为 0.bmp、1.bmp,最多 31 个。它们也存储在一个名为“tiles”的文件夹中,但将它们从该文件夹中取出不会有任何变化。
    • @Naberius 然后尝试使用 File file = new File("tiles"+i+".bmp");这个。
    【解决方案3】:

    尝试将 InputStream 包装到 BufferedInputStream 中:

    fis = new FileInputStream(file); ==> new BufferedInputStream(new FileInputStream(file));

    【讨论】:

      【解决方案4】:

      使用new File(getClass().getResource("tiles\\"+i+".bmp"));

      【讨论】:

        猜你喜欢
        • 2014-11-08
        • 2016-05-28
        • 1970-01-01
        • 2021-12-15
        相关资源
        最近更新 更多