javax.imageio.ImageIO创建ImageInputStream时出现问题

我在Tomcat 5.5中有一个Servlet,可以读取坐在文件夹中的本地图像.然后将图像发送回Applet.

我收到此“ javax.imageio.IIOException:无法创建ImageInputStream!”错误,不确定是什么原因引起的.

有人遇到过这个问题吗?这可能是ImageIO中的线程问题吗?我无法重现此问题,因为每1000个请求大约发生3次.

编辑:这是读取图像的Servlet代码.我只是在Servlet的doPost方法中以其静态形式使用ImageIO.read(File),如下所示:

    doPost(req,resp){
       ...
        BufferedImage image = ImageIO.read(imageFile);
       ...
    }

这是javax.imageio.ImageIO.read(File)的源代码:

    public static BufferedImage read(File input) throws IOException {
    if (input == null) {
        throw new IllegalArgumentException("input == null!");
    }
    if (!input.canRead()) {
        throw new IIOException("Can't read input file!");
    }

    ImageInputStream stream = createImageInputStream(input);
    if (stream == null) {
        throw new IIOException("Can't create an ImageInputStream!");
    }
    BufferedImage bi = read(stream);
    if (bi == null) {
        stream.close();
    }
    return bi;
    }

解决方法:

我的消息源(Java5,但我怀疑它已经发生了很大变化)指出,如果没有注册ImageInputStream服务提供者,则createImageInputStream方法将返回null,因此您将获得该异常.

从ImageIO使用的IIORegistry.getDefaultInstance()上的JavaDoc:

Each ThreadGroup will receive its own instance; this allows different Applets in the same browser (for example) to each have their own registry.

因此,实际上可能是线程问题,因为您获得了一个普通的IIORegistry新实例.

编辑:深入研究源代码,我发现以下内容:

由于您传入了文件,因此很可能会得到FileImageInputStream.但是,如果发生异常,服务提供商将返回null.因此,可能会引发FileNotFoundException或引发任何其他IOException,从而导致无法创建流.

不幸的是,没有登录代码,因此您必须以某种方式进行调试.可能是由于缺少文件权限,文件损坏/不完整或文件丢失.

这是FileImageInputStreamSpi#createInputStreamInstance()的Java5源

public ImageInputStream createInputStreamInstance(Object input,
                                                  boolean useCache,
                                                  File cacheDir) {
    if (input instanceof File) {
        try {
            return new FileImageInputStream((File)input);
        } catch (Exception e) {
            return null;
        }
    } else {
        throw new IllegalArgumentException();
    }
}
上一篇:Ngrok让你的本地Web应用暴露在公网上


下一篇:在Java 1.4 InputStream上替换char