Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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

like image 347
2FaceMan Avatar asked Jul 18 '14 11:07

2FaceMan


1 Answers

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);
like image 126
akash Avatar answered Oct 12 '22 15:10

akash