如何使 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 15:02:07  来源:igfitidea点击:

How to make ImageIO read from InputStream :Java

javaimagefile-ioexecutable-jarjavax.imageio

提问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因为ImageInputStreamInputStreamReader您想到的无关。

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);

回答by Brett Okken

The ImageIOclass has a utility method to readan InputStreamand create a BufferedImage.

ImageIO班有一个实用的方法来InputStream,并创建一个BufferedImage

There is also a utility method to createan ImageInputStreamfrom an InputStream.

还有一个实用的方法来创建一个ImageInputStreamInputStream