首页javaimageJava Graphics - 如何从URL下载图像

Java Graphics - 如何从URL下载图像

我们想知道如何从URL下载图像。
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;

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.w3cschool.cn/style/download.png");

  }
}