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
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With