【问题标题】:Using ImageIO.read with a redirecting URL使用带有重定向 URL 的 ImageIO.read
【发布时间】:2011-01-31 14:20:54
【问题描述】:

我正在尝试使用 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。

两个问题。一,为什么会这样?是不是因为 ImageIO 库试图根据 URL 字符串找到合适的 ImageReader?第二,解决这个限制的最干净的解决方案是什么?请注意,我需要 BufferedImage 输出而不是 Image 输出。

编辑:对于想要测试它的人来说,我正在尝试读取的 URL 是 http://graph.facebook.com/804672289/picture,它被转换为 http://profile.ak.fbcdn.net/hprofile-ak-snc4/hs351.snc4/41632_804672289_6662_q.jpg.

编辑 2:我在上次编辑中不正确。网址是https://graph.facebook.com/804672289/picture。如果我用 http 替换 https,上面的代码可以正常工作。所以我的新问题是如何让它与 HTTPS 一起工作,这样我就不需要更换了。

【问题讨论】:

  • 这很奇怪。 ImageIO 使用默认 URL 设置,其中包括“followRedirects=true”
  • 我有一个关于重定向 url 的相同问题的变体,只是对于每次调用 ImageIO.read(url) 时,返回的图像要么为空,要么每隔一段时间不为空..

标签: java http javax.imageio jai


【解决方案1】:

在我看来,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

我怀疑你的错误在其他地方。

【讨论】:

  • 问题是我使用的 URL 是 https:// 而不是 http://。问题是为什么我所看到的只是 bi 变为空,而不是一些错误 - 我如何在不将 https 替换为 http 的情况下克服这个问题。
【解决方案2】:

我在使用 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();
    }

【讨论】:

    【解决方案3】:

    关于您的编辑 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);
                    }
        }
    

    【讨论】:

      【解决方案4】:

      目前可以使用 Apache HttpClient,对我来说效果很好。

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-09-14
        • 2017-07-30
        • 1970-01-01
        • 2013-01-13
        相关资源
        最近更新 更多