您好,我正在尝试从网页下载图像。我正在尝试从“ http://www.yahoo”主页下载该图像。请告诉我如何传递“ http://www.yahoo”作为输入。以及在打开此网页时如何从该页面获取图像。请给我Java代码以从网页获取图像。
(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图片。否则,您可以执行以下操作:
javax.imageio
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();
然后您可能想要保存图像,这样:
FileOutputStream fos = new FileOutputStream("C://borrowed_image.jpg"); fos.write(response); fos.close();