Java Graphics How to - Download an image from a URL








Question

We would like to know how to download an image from a URL.

Answer

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
//  www  .  j  av  a2  s.com
public class Main {
  public static byte[] downloadImageFromURL(String strUrl)
      throws Exception {
    InputStream in;
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    URL url = new URL(strUrl);
    in = new BufferedInputStream(url.openStream());
    byte[] buf = new byte[2048];
    int n = 0;
    while (-1 != (n = in.read(buf))) {
      out.write(buf, 0, n);
    }
    out.close();
    in.close();
    byte[] response = out.toByteArray();
    FileOutputStream fos = new FileOutputStream("/Users/image.jpg");
    fos.write(response);
    fos.close();
    return response;
  }

  public static void main(String[] args) throws Exception {
    downloadImageFromURL("http://www.java2s.com/style/download.png");

  }
}