如何从java中的任何网页下载图像 [英] how to download image from any web page in java

查看:111
本文介绍了如何从java中的任何网页下载图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

hi
我正在尝试从网页下载图片。
我想从'http://www.yahoo.com'主页下载图片。
请告诉我如何通过'http://www.yahoo.com'作为输入。
打开此网页后,如何从此页面获取图像。
请给我java代码从网页上获取图片。

hi I am trying to download image from web page. I am trying to download the image from 'http://www.yahoo.com' home page. Please tell me how to pass 'http://www.yahoo.com' as a input. And on opening this web page how to fetch image from this page. Please give me java code to fetch the image from web page.

推荐答案

(throws IOException)

Image image = null;
try {
    URL url = new URL("http://www.yahoo.com/image_to_read.jpg");
    image = ImageIO.read(url);
} catch (IOException e) {
}

参见 javax.imageio 包以获取更多信息。这是使用AWT图像。否则你可以这样做:

See javax.imageio package for more info. That's using the AWT image. Otherwise you could do:

 URL url = new URL("http://www.yahoo.com/image_to_read.jpg");
InputStream in = new BufferedInputStream(url.openStream());
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int n = 0;
while (-1!=(n=in.read(buf)))
{
   out.write(buf, 0, n);
}
out.close();
in.close();
byte[] response = out.toByteArray();

然后您可能想要保存图像,这样做:

And you may then want to save the image so do:

FileOutputStream fos = new FileOutputStream("C://borrowed_image.jpg");
fos.write(response);
fos.close();

这篇关于如何从java中的任何网页下载图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆