从 URL 获取图像 (Java)

新手上路,请多包涵

我正在尝试阅读下图

在此处输入图像描述

但它正在显示 IIOException。

这是代码:

 Image image = null;
URL url = new URL("http://bks6.books.google.ca/books?id=5VTBuvfZDyoC&printsec=frontcover&img=1& zoom=5&edge=curl&source=gbs_api");
image = ImageIO.read(url);
jXImageView1.setImage(image);

原文由 Nav Ali 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 535
2 个回答

您收到 HTTP 400 (错误请求)错误,因为 space 在您的 URL 中。如果修复它(在 zoom 参数之前),您将得到一个 HTTP 401 错误(未经授权)。也许您需要一些 HTTP 标头来将您的下载标识为可识别的浏览器(使用“用户代理”标头)或其他身份验证参数。

对于 User-Agent 示例,然后使用连接输入流使用 ImageIO.read(InputStream)

 URLConnection connection = url.openConnection();
connection.setRequestProperty("User-Agent", "xxxxxx");

使用 xxxxxx

原文由 JScoobyCed 发布,翻译遵循 CC BY-SA 4.0 许可协议

这段代码对我来说很好用。

  import java.io.FileOutputStream;
 import java.io.IOException;
 import java.io.InputStream;
 import java.io.OutputStream;
 import java.net.URL;

public class SaveImageFromUrl {

public static void main(String[] args) throws Exception {
    String imageUrl = "http://www.avajava.com/images/avajavalogo.jpg";
    String destinationFile = "image.jpg";

    saveImage(imageUrl, destinationFile);
}

public static void saveImage(String imageUrl, String destinationFile) throws IOException {
    URL url = new URL(imageUrl);
    InputStream is = url.openStream();
    OutputStream os = new FileOutputStream(destinationFile);

    byte[] b = new byte[2048];
    int length;

    while ((length = is.read(b)) != -1) {
        os.write(b, 0, length);
    }

    is.close();
    os.close();
}

}

原文由 swapnil gandhi 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题