How to make ImageIO read from InputStream :Java

半城伤御伤魂 提交于 2019-12-06 01:18:04

问题


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 /images folder in the project . Code has to access these file to create BufferedImage using ImageIO.read(new File(path);

Earlier, To get the path I used ClassName.class.getResource(/image/test.png).toURI();

On executing jar , it throw error URI is not hierarchical

So now I am using ClassName.class.getResourceAsStream(/image/test.png);

But how to make ImageIO read from Inputstream ? 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


回答1:


ImageIO.read() takes InputStream as a parameter so there is no meaning of casting it to ImageInputStream.

Secondly you can not cast an InputStreamReader object to ImageInputStream because ImageInputStream has nothing to do with InputStreamReader which you thought of.

Moreover getResourceAsStream() returns InputStream. So you can directly do it like this.

InputStream resourceBuff = YourClass.class.getResourceAsStream(filepath);
BufferedImage bf = ImageIO.read(resourceBuff);



回答2:


The ImageIO class has a utility method to read an InputStream and create a BufferedImage.

There is also a utility method to create an ImageInputStream from an InputStream.



来源:https://stackoverflow.com/questions/24824353/how-to-make-imageio-read-from-inputstream-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!