I need to load an image from a web in a simple Java stand alone aplication. Any Ideas?
Asked
Active
Viewed 4.9k times
4 Answers
60
You can load an image using
BufferedImage img = ImageIO.read(new URL("http://stackoverflow.com/content/img/so/logo.png"));
For methods how to display the loaded image, see the Sun "Working with images" tutorial.

rodion
- 6,087
- 4
- 24
- 29
-
This results in `null` if the URL has http status code `301` or `302`. If so, look at https://stackoverflow.com/questions/14951696/java-urlconnection-get-the-final-redirected-url. – dr0i Nov 28 '19 at 15:02
12
URL url = new URL("http://host/theimage.jpg");
URLConnection conn = url.openConnection();
InputStream in = conn.getInputStream();
is that enough to start you? Don't know what you want to do from there.

FuryFart
- 2,304
- 4
- 27
- 43

Gary Kephart
- 4,860
- 5
- 39
- 52
-
4
-
1you can do `Files.copy(url.openStream(), new File("filename.jpg").toPath());` to store it on disk(watch out for null-pointers). – rupinderjeet Jul 03 '16 at 09:53
3
I would take a look at HTTPClient.
Find the URL to the image, and you can get an inputstream feeding you the image data, plus you'll get the content-type etc. so you can correctly handle it once you've downloaded it.
Here's some sample code. You may also need to call getResponseHeaders() on the GetMethod to identify the image type.

Brian Agnew
- 268,207
- 37
- 334
- 440