本文介绍了如何从InputStream:Java中读取ImageIO的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经创建了可执行的jar文件(使用Eclipse),有一组图像(.png)文件将被包含在jar中。所以我在项目中添加了一个包含 / images 文件夹内所有图像的源文件夹。代码必须使用 ImageIO.read(new File(path);



创建BufferedImage,
获取我使用的路径 ClassName.class.getResource(/image/test.png).toURI();



在执行jar时,它抛出错误URI不是分层的

所以现在我正在使用 ClassName.class.getResourceAsStream(/image/test.png);



但是如何让ImageIO从InputStream中读取?
I尝试投射如下

  InputStreamReader resourceBuff = ClassName.class.getResourceAsStream(/image/test.png); 
ImageIO .read((ImageInputStream)new InputStreamReader(resourceBuff));

引发错误InputStreamReader不能被转换为ImageInputStream

解决方案

将 InputStream 作为参数,因此不会将其转换为 ImageInputStream 。



其次,您不能将 InputStreamReader 对象转换为因为 ImageInputStream 与您想到的 InputStreamReader 无关。



此外返回 InputStream 。所以你可以直接这样做。

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


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

这篇关于如何从InputStream:Java中读取ImageIO的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 19:06