URLから画像を取得する(Java)質問する

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

ベストアンサー1

このコードは私にとっては問題なく動作しました。

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

}

おすすめ記事