How to make ImageIO read from InputStream :Java

2FaceMan picture 2FaceMan · Jul 18, 2014 · Viewed 15.7k times · Source

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

Answer

CoderCroc picture CoderCroc · Jul 18, 2014

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