In this example, let’s see how to read an image from file or URL.
Source Code
package com.beginner.examples;
import java.awt.Image;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class ReadImageFromFileOrURL {
public static void main(String[] args) {
try {
URL url = new URL("https://gss0.bdstatic.com/70cFsjip0QIZ8tyhnq/img/logo-zhidao.gif");
File file = new File("E:tmplogo-zhidao.gif");
Image image = ImageIO.read(file);
JFrame frame = new JFrame();
frame.setSize(300, 300);
JLabel label = new JLabel(new ImageIcon(image));
frame.add(label);
frame.setVisible(true);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
References
Imported packages in Java documentation: