[英]How to make ImageIO read from InputStream :Java
I have created executable jar file(using Eclipse) , there are a set of image (.png) files that is to be inculded in the jar. 我已经创建了可执行jar文件(使用Eclipse),有一组图像(.png)文件将被包含在jar中。 So I have added a source folder with all the images inside
/images
folder in the project . 所以我添加了一个源文件夹,其中包含项目中
/images
文件夹中的所有图像。 Code has to access these file to create BufferedImage using ImageIO.read(new File(path);
代码必须访问这些文件才能使用
ImageIO.read(new File(path);
创建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不是分层的
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 ? 但是如何从Inputstream读取ImageIO? I tried cast as follows
我尝试演员如下
InputStreamReader resourceBuff=ClassName.class.getResourceAsStream(/image/test.png);
ImageIO.read((ImageInputStream) new InputStreamReader(resourceBuff));
It throws error InputStreamReader cannot be cast to ImageInputStream 它抛出错误InputStreamReader无法强制转换为ImageInputStream
ImageIO.read()
takes InputStream
as a parameter so there is no meaning of casting it to ImageInputStream
. ImageIO.read()
将InputStream
作为参数,因此没有意义将其强制转换为ImageInputStream
。
Secondly you can not cast an InputStreamReader
object to ImageInputStream
because ImageInputStream
has nothing to do with InputStreamReader
which you thought of. 其次,您无法将
InputStreamReader
对象ImageInputStream
为ImageInputStream
因为ImageInputStream
与您想到的InputStreamReader
无关。
Moreover getResourceAsStream()
returns InputStream
. 此外,
getResourceAsStream()
返回InputStream
。 So you can directly do it like this. 所以你可以直接这样做。
InputStream resourceBuff = YourClass.class.getResourceAsStream(filepath);
BufferedImage bf = ImageIO.read(resourceBuff);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.