如何使 ImageIO 从 InputStream 读取:Java
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24824353/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to make ImageIO read from InputStream :Java
提问by 2FaceMan
I have created executable jar file(using Eclipse) , there are a set of image (.png) files that is to be inculded in the jar. So I have added a source folder with all the images inside /imagesfolder in the project . Code has to access these file to create BufferedImage using ImageIO.read(new File(path);
我已经创建了可执行 jar 文件(使用 Eclipse),有一组图像 (.png) 文件将被包含在 jar 中。所以我在项目中添加了一个包含所有图像的源文件/images夹。代码必须访问这些文件以创建 BufferedImage 使用ImageIO.read(new File(path);
Earlier,
To get the path I used ClassName.class.getResource(/image/test.png).toURI();
早些时候,为了获得我使用的路径 ClassName.class.getResource(/image/test.png).toURI();
On executing jar , it throw error URI is not hierarchical
在执行 jar 时,它抛出错误 URI is not hierarchy
So now I am using ClassName.class.getResourceAsStream(/image/test.png);
所以现在我正在使用 ClassName.class.getResourceAsStream(/image/test.png);
But how to make ImageIO read from Inputstream ? I tried cast as follows
但是如何让 ImageIO 从 Inputstream 读取?我试过如下
InputStreamReader resourceBuff=ClassName.class.getResourceAsStream(/image/test.png);
ImageIO.read((ImageInputStream) new InputStreamReader(resourceBuff));
It throws error InputStreamReader cannot be cast to ImageInputStream
它抛出错误InputStreamReader cannot be cast to ImageInputStream
采纳答案by CoderCroc
ImageIO.read()takes InputStreamas a parameter so there is no meaning of casting it to ImageInputStream.
ImageIO.read()将其InputStream作为参数,因此将其强制转换为ImageInputStream.
Secondly you can not cast an InputStreamReaderobject to ImageInputStreambecause ImageInputStreamhas nothing to do with InputStreamReaderwhich you thought of.
其次,您不能将InputStreamReader对象投射到,ImageInputStream因为ImageInputStream与InputStreamReader您想到的无关。
Moreover getResourceAsStream()returns InputStream. So you can directly do it like this.
而且还getResourceAsStream()回来InputStream。所以你可以直接这样做。
InputStream resourceBuff = YourClass.class.getResourceAsStream(filepath);
BufferedImage bf = ImageIO.read(resourceBuff);

