1

ImageIOを使用してネットから画像を読み取ろうとしています。

URL url = new URL(location);
bi = ImageIO.read(url);

locationが実際の画像で終わるURL(例:http ://www.lol.net/1.jpg)の場合、上記のコードは機能します。ただし、URLがリダイレクトである場合(たとえば、 http : //www.lol.net/redirection、http ://www.lol.net/1.jpgにつながる)、上記のコードはbiでnullを返します。

2つの質問。一つ、なぜこれが起こっているのですか?ImageIOライブラリがURL文字列に基づいて適切なImageReaderを見つけようとするためですか?そして2つ目は、この制限に対する最もクリーンな解決策は何でしょうか。画像出力ではなく、BufferedImage出力が必要であることに注意してください。

編集:それをテストしたい人のために、私が読み込もうとしているURLはhttp://graph.facebook.com/804672289/pictureであり、これはhttp://profile.ak.fbcdn.net/hprofile-に変換され ます。 ak-snc4 / hs351.snc4/41632_804672289_6662_q.jpg

編集2:私は最後の編集で間違っていました。URLはhttps://graph.facebook.com/804672289/pictureです。httpsをhttpに置き換えると、上記のコードは正常に機能します。ですから、私の新しい質問は、HTTPSで動作させる方法です。これにより、置換を行う必要がなくなります。

4

4 に答える 4

4

私には、http://www.lol.net/1.jpgが画像を直接指しているようには見えません。

@Bozhoが指摘しているように、ImageIOはデフォルトURL.openConnectionを使用します(アドレスは「http」で始まるため) 。HttpURLConnectionこれは、デフォルトごとに。を返しますsetFollowRedirects(true)

あなたの編集に関して、このコードは私にはうまく機能しているようです:

URL url = new URL("http://graph.facebook.com/804672289/picture");
BufferedImage bi = ImageIO.read(url);

System.out.println(bi);
// Prints: BufferedImage@43b09468: type = 5 ColorModel: #pixelBits = 24 numComponents = 3 color space = java.awt.color.ICC_ColorSpace@7ddf5a8f transparency = 1 has alpha = false isAlphaPre = false ByteInterleavedRaster: width = 50 height = 50 #numDataElements 3 dataOff[0] = 2

あなたのエラーはどこかにあると思います。

于 2011-01-31T14:25:50.313 に答える
4

https画像リンクでも同じ問題が発生していました。問題は、コードでhttpsリンクを読み取ると、200が返されることでした。しかし、実際には301でした。この問題を回避するために、「curl」ユーザーエージェントを使用して、 301そして最後のリンクが見つかるまで繰り返します。以下のコードを参照してください。

これが@Eldad-Morに役立つことを願っています。

private InputStream getInputStream(String url) throws IOException {
        InputStream stream = null;
        try {
            stream = handleRedirects(url);
            byte[] bytes = IOUtils.toByteArray(stream);
            return new ByteArrayInputStream(bytes);
        } finally {
            if (stream != null)
                stream.close();
        }
    }

    /**
     * Handle redirects in the URL Manually. Method calls itself if redirects are found until there re no more redirects.
     * 
     * @param url URL
     * @return input stream
     * @throws IOException
     */
    private InputStream handleRedirects(String url) throws IOException {
        HttpURLConnection.setFollowRedirects(false);
        URL obj = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
        conn.setRequestProperty("User-Agent", "curl/7.30.0");
        conn.connect();
        boolean redirect = false;
        LOG.info(conn.getURL().toString());

        int status = conn.getResponseCode();
        if (status != HttpURLConnection.HTTP_OK) {
            if (status == HttpURLConnection.HTTP_MOVED_TEMP
                    || status == HttpURLConnection.HTTP_MOVED_PERM
                    || status == HttpURLConnection.HTTP_SEE_OTHER)
                redirect = true;
        }
        if (redirect) {
            String newUrl =conn.getHeaderField("Location");
            conn.getInputStream().close();
            conn.disconnect();
            return handleRedirects(newUrl);
        }
        return conn.getInputStream();
    }
于 2014-09-12T12:05:30.280 に答える
2

あなたの編集について2:

ImageIo.read(url)は、URLタイプを気にしません。つまり、httpまたはhttpsです。

このメソッドにURLを渡すだけで済みますが、https urlを渡す場合は、SSL証明書を検証するために特定の手順を実行する必要があります。以下の例をご覧ください。

1)httpおよびhttpsの場合:

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.cert.X509Certificate;
import javax.imageio.ImageIO;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;


/**
 * @author Syed CBE
 *
 */
public class Main {


    public static void main(String[] args) {

                int height = 0,width = 0;
                String imagePath="https://www.sampledomain.com/sampleimage.jpg";
                System.out.println("URL=="+imagePath);
                InputStream connection;
                try {
                    URL url = new URL(imagePath);  
                    if(imagePath.indexOf("https://")!=-1){
                        final SSLContext sc = SSLContext.getInstance("SSL");
                        sc.init(null, getTrustingManager(), new java.security.SecureRandom());                                 
                        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
                        connection = url.openStream();
                     }
                    else{
                        connection = url.openStream();
                    }
                    BufferedImage bufferedimage = ImageIO.read(connection);
                    width          = bufferedimage.getWidth();
                    height         = bufferedimage.getHeight();
                    System.out.println("width="+width);
                    System.out.println("height="+height);
                } catch (MalformedURLException e) {

                    System.out.println("URL is not correct : " + imagePath);
                } catch (IOException e) {

                    System.out.println("IOException Occurred : "+e);
                }
                catch (Exception e) {

                    System.out.println("Exception Occurred  : "+e);
                }


    }

     private static TrustManager[] getTrustingManager() {
            TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

                   @Override
                   public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                         return null;
                   }

                   @Override
                   public void checkClientTrusted(X509Certificate[] certs, String authType) {
                   }

                   @Override
                   public void checkServerTrusted(X509Certificate[] certs, String authType) {
                   }
            } };
            return trustAllCerts;
     }

}

2)httpのみの場合:

// This Code will work only for http, you can make it work for https but you need additional code to add SSL certificate using keystore
    public static void getImage(String testUrl) {

            String testUrl="https://sampleurl.com/image.jpg";

        HttpGet httpGet = new HttpGet(testUrl);
                 System.out.println("HttpGet is  ---->"+httpGet.getURI());
                HttpResponse httpResponse = null;
                HttpClient httpClient=new DefaultHttpClient();

                try {

                    httpResponse = httpClient.execute(httpGet);
                    InputStream stream=httpResponse.getEntity().getContent();
                     BufferedImage sourceImg = ImageIO.read(stream);
                    System.out.println("------ source -----"+sourceImg.getHeight());
                     sourceImg.getWidth();
                        System.out.println(sourceImg);
                }catch (MalformedURLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    System.out.println("------ MalformedURLException -----"+e);
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                System.out.println("------  IOEXCEPTION -----"+e);
                }
    }
于 2015-05-25T15:05:58.910 に答える
0

momemntではApacheHttpClientを使用できますが、私にとっては問題なく動作します。

http://hc.apache.org/

    public static void main(String args[]) throws Exception{
    String url = "http://graph.facebook.com/804672289/picture?width=800";

    HttpClient client = HttpClients.createDefault();
    HttpResponse response = client.execute(new HttpGet(url));
    BufferedImage image = ImageIO.read(input);

    if(image == null){
        throw new RuntimeException("Ooops");
    } else{
        System.out.println(image.getHeight());
    }
}
于 2015-04-19T08:39:36.640 に答える