Last active
December 6, 2019 07:32
-
-
Save aslamanver/92af3ac67406cfd116b7e4e177156926 to your computer and use it in GitHub Desktop.
Show image to JFrame from URL
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.awt.BorderLayout; | |
import java.awt.Image; | |
import java.io.IOException; | |
import java.io.InputStream; | |
import java.net.URL; | |
import java.net.URLConnection; | |
import javax.imageio.ImageIO; | |
import javax.swing.ImageIcon; | |
import javax.swing.JFrame; | |
import javax.swing.JLabel; | |
public class ShowImageFromURL { | |
/** | |
* Displays an image read from an URL within a JFrame. | |
* | |
* @param urlLocation An URL pointing to a image. | |
*/ | |
public static void show(String urlLocation) { | |
Image image = null; | |
try { | |
URL url = new URL(urlLocation); | |
URLConnection conn = url.openConnection(); | |
conn.setRequestProperty("User-Agent", "Mozilla/5.0"); | |
conn.connect(); | |
InputStream urlStream = conn.getInputStream(); | |
image = ImageIO.read(urlStream); | |
JFrame frame = new JFrame(); | |
JLabel lblimage = new JLabel(new ImageIcon(image)); | |
frame.getContentPane().add(lblimage, BorderLayout.CENTER); | |
frame.setSize(image.getWidth(null) + 50, image.getHeight(null) + 50); | |
frame.setVisible(true); | |
} catch (IOException e) { | |
System.out.println("Something went wrong, sorry:" + e.toString()); | |
e.printStackTrace(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment