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

两个问题。一,为什么会这样?是不是因为 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 一起工作,所以我不需要进行替换。

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

目前可以使用 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());
    }
}
于 2015-04-19T08:39:36.640 回答