You can use something like this if you are trying to load an image from a local location.
File file = new File("D:/project/resources/imageA.jpg");
Image image = ImageIO.read(file);
If you are planning to read the image from a URL, use the below code:
URL url = new URL("http://www.google.co.in/images/srpr/logo3w.png");
Image image = ImageIO.read(url);
Please have a look at the below code for better understanding:
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();
}
}
Output

