25

I need to load an image from a web in a simple Java stand alone aplication. Any Ideas?

4 Answers4

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
5

See the documentation at ImageIO.read(URL).

Dave Jarvis
  • 30,436
  • 41
  • 178
  • 315
iny
  • 7,339
  • 3
  • 31
  • 36
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