26

次の画像を読み取ろうとしています

ここに画像の説明を入力

しかし、それは 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); 
4

6 に答える 6

21

このコードは私にとってはうまくいきました。

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

}
于 2014-10-07T10:56:13.783 に答える
13

URLにが含まれているため、HTTP 400(不正なリクエスト)エラーが発生spaceします。zoom(パラメーターの前に)修正すると、HTTP 401エラー(無許可)が発生します。ダウンロードを認識されたブラウザ(「User-Agent」ヘッダーを使用)または追加の認証パラメータとして識別するために、HTTPヘッダーが必要になる場合があります。

User-Agentの例では、接続inputstreamを使用してImageIO.read(InputStream)を使用します。

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

必要なものは何でも使用してくださいxxxxxx

于 2012-04-24T06:45:26.533 に答える
4

画像を取得するために URL を直接呼び出すと、重大なセキュリティの問題が発生する可能性があります。そのリソースにアクセスするための十分な権限があることを確認する必要があります。ただしByteOutputStream、画像ファイルの読み取りには使用できます。これは一例です (これは単なる例です。必要に応じて必要な変更を行う必要があります。)

ByteArrayOutputStream bis = new ByteArrayOutputStream();
InputStream is = null;
try {
  is = url.openStream ();
  byte[] bytebuff = new byte[4096]; 
  int n;

  while ( (n = is.read(bytebuff)) > 0 ) {
    bis.write(bytebuff, 0, n);
  }
}
于 2012-04-24T06:41:59.497 に答える
1

試す:

public class ImageComponent extends JComponent {
  private final BufferedImage img;

  public ImageComponent(URL url) throws IOException {
    img = ImageIO.read(url);
    setPreferredSize(new Dimension(img.getWidth(), img.getHeight()));

  }

  @Override
  protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.drawImage(img, 0, 0, img.getWidth(), img.getHeight(), this);
  }

  public static void main(String[] args) throws Exception {
    final URL kitten = new URL("https://placekitten.com/g/200/300");

    final ImageComponent image = new ImageComponent(kitten);

    JFrame frame = new JFrame("Test");
    frame.add(new JScrollPane(image));

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(400, 300);
    frame.setVisible(true);
  }
}
于 2012-04-24T06:49:55.553 に答える