通过BufferedImage从文件路径加载图像 [英] Load image from a filepath via BufferedImage
问题描述
我的Java应用程序存在问题,特别是在从计算机中的某个位置加载图像时。
关注这个帖子
我使用BufferedImage和InputFileStream在我的计算机中加载图像
首先,我将pic2.jpg图像放入源代码中,没关系。然而,第二,我把这个图像放到另一个地方(在这种情况下是C:\ ImageTest \ pic2.jpg),Java IDE在行显示IllegalArgumentExceptioninput == null
I have a problem with Java application, particular in loading a image from a location in my computer. Follow this post I use BufferedImage and InputFileStream to load a image in my computer First, I put the pic2.jpg image into the source code, it's fine. However, second, i put this image into another place (C:\ImageTest\pic2.jpg in this case), Java IDE show me an IllegalArgumentException "input == null" at line
return ImageIO.read(in);
。我去谷歌搜索确保,我放入代码的链接形式是正确的,所以,我不知道我在哪里做错了....
. I go to google search to make sure that, the form of link that I put into a code is correct, so, i don't know where i did wrong....
这里是代码:
public class MiddlePanel extends JPanel {
private BufferedImage img;
public MiddlePanel(int width){
//img = getImage("pic2.jpg");
img = getImage("C:\\ImageTest\\pic2.jpg");
this.setPreferredSize(new Dimension(800,460));
}
public void paintComponent(Graphics g) {
.....
}
private BufferedImage getImage(String filename) {
// This time, you can use an InputStream to load
try {
// Grab the InputStream for the image.
InputStream in = getClass().getResourceAsStream(filename);
// Then read it in.
return ImageIO.read(in);
} catch (IOException e) {
System.out.println("The image was not loaded.");
//System.exit(1);
}
return null;
}
推荐答案
getResource
& getResourceAsStream
不使用文件路径,而是使用相对于代码库的路径。如果代码库是 C:
那么找到资源的相对路径是 /ImageTest/pic2.jpg
。
getResource
& getResourceAsStream
do not work with file paths, but paths relative the code base. If the code base is C:
then a relative path that would locate the resource is /ImageTest/pic2.jpg
.
..加载文件之间的区别
FileInputStream
和getResourceAsStream
?
一个主要的区别是 getResource ..
将使用Jar内的资源,该资源不再是文件
。因此 FileInputStream
无法用于访问此类资源。
One major difference is that the getResource..
will work with a resource inside a Jar, which is no longer a File
. Therefore FileInputStream
cannot be used to access such a resource.
这篇关于通过BufferedImage从文件路径加载图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!