从URL获取图像(Java)

Nav*_*Ali 23 java url image

我正在尝试阅读以下图片

在此输入图像描述

但它显示了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); 
Run Code Online (Sandbox Code Playgroud)

swa*_*dhi 19

这段代码对我来说很好.

 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();
}

}
Run Code Online (Sandbox Code Playgroud)


JSc*_*Ced 10

您收到HTTP 400(错误请求)错误,因为space您的网址中有一个错误.如果您修复它(在zoom参数之前),您将收到HTTP 400错误(未经授权).也许您需要一些HTTP标头来将您的下载标识为可识别的浏览器(使用"User-Agent"标头)或其他身份验证参数.

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

URLConnection connection = url.openConnection();
connection.setRequestProperty("User-Agent", "xxxxxx");
Run Code Online (Sandbox Code Playgroud)

使用所需的一切 xxxxxx

  • 我添加了一个例子. (2认同)

小智 10

试试这个:

//urlPath = address of your picture on internet
URL url = new URL("urlPath");
BufferedImage c = ImageIO.read(url);
ImageIcon image = new ImageIcon(c);
jXImageView1.setImage(image);
Run Code Online (Sandbox Code Playgroud)