我在Eclipse中创建了一个名为“resources”的新文件夹,并将我的所有图片放在其中。我将此文件夹添加到类路径中。
现在我尝试访问这些图片。
URL url = new URL("imageA");
我也尝试过。
URL url = new URL("resources/imageA");
两个都不起作用。出了什么问题?
真诚地 克里斯蒂安
InputSteam is = this.getClass().getClassLoader().getResourceAsStream("resources/myimage.png")
File file = new File("D:/project/resources/imageA.jpg");
Image image = ImageIO.read(file);
如果您计划从URL读取图像,请使用以下代码:
URL url = new URL("http://www.google.co.in/images/srpr/logo3w.png");
Image image = ImageIO.read(url);
package com.stack.overflow.works.main;
import java.awt.Image;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
/**
* @author sarath_sivan
*/
public class ImageLoader {
private ClassLoader classLoader = ClassLoader.getSystemClassLoader();
private Image image = null;
private URL url = null;
/**
* Loading image from a URL with the help of java.net.URL class.
*/
public void loadFromURL() {
image = null;
try {
url = new URL("http://www.google.co.in/images/srpr/logo3w.png");
if (url != null) {
image = ImageIO.read(url);
}
} catch(Exception exception) {
exception.printStackTrace();
}
display(image, "Loading image from URL...");
}
/**
* Loading image from your local hard-drive with getResource().
* Make sure that your resource folder which contains the image
* is available in your class path.
*/
public void loadFromLocalFile() {
image = null;
try {
url = classLoader.getResource("images.jpg");
if (url != null) {
image = ImageIO.read(url);
}
} catch(Exception exception) {
exception.printStackTrace();
}
display(image, "Loading image from Local File...");
}
private void display(Image image, String message) {
JFrame frame = new JFrame(message);
frame.setSize(300, 300);
JLabel label = new JLabel(new ImageIcon(image));
frame.add(label);
frame.setVisible(true);
}
public static void main(String[] args) {
ImageLoader imageLoader = new ImageLoader();
imageLoader.loadFromURL();
imageLoader.loadFromLocalFile();
}
}
输出