简体   繁体   中英

Why use ImageIO can't get BufferedImage from URL

imageURL: https://fbexternal-a.akamaihd.net/safe_image.php?d=AQBB77GLfY75FNWL&w=720&h=2048&url=http%3A%2F%2Fwww.facebook.com%2Fads%2Fimage%2F%3Fd%3DAQI0duFYFcmydWNutbwmSk2DfOmHcDrhPfsMJTUoEObbWkVzYUtrHgCuN_LFrWcPRzJi6jPgbn80oFs0Kj_WrdROjdnJkjbnS5-UJv9l9cJyhKCWS-lr-MXlc263Ul3Txe-VFqXfRrA6BOjt4DF-Sww2&ext=best

URL url = new URL(imageURL);
BufferedImage image = ImageIO.read(url);

or

URL url = new URL(imageURL);
BufferedImage image = ImageIO.read(url.openStream());

the result image is null? why?

ImageIO.read(URL) does support reading images from URL like you describe, however, it does support only a limited set of image formats. Built-in formats are JPEG, PNG, GIF, BMP and WBMP. There are plugins for many other formats, like TIFF, JPEG 2000, etc.

The problem is that the linked image is not in any of the built-in formats, it's in WEBP format , a new image format created by Google, and which does not have very widespread use yet. The reason it displays fine in your browser (and mine :-) ), is most likely that you are using Chrome, and Chrome has built-in support for WEBP.

There's at least one WEBP ImageIO plugin available. If you build and install this plugin, your code above should work and read the image just fine. There should be no need to invoke ImageIO.scanForPlugins() if the plugin is on class path when you launch your application.

Make sure the URL your provided is linking to a valid image file format such as jpg , png , bmp and so on.

Your current URL is linking to a .php file which is obviously not an image.

For example:

在此输入图像描述

public static void main(String[] args)
{     
    Image image = null;
    try {
        URL url = new URL("https://s-media-cache-ak0.pinimg.com/236x/ac/bb/d4/acbbd49b22b8c556979418f6618a35fd.jpg");
        image = ImageIO.read(url);
    } catch (IOException e) {
        e.printStackTrace();
    }

    JFrame frame = new JFrame();
    frame.setSize(236, 306);
    frame.add(new JLabel(new ImageIcon(image)));
    frame.setVisible(true);                 
}

When I open the link in Firefox, it attempts to download a file called "safe_image.php". It works in Google Chrome, so there's something weird going on in the headers or something for that URL. Is there any way you can host the image elsewhere?

Edit: Your image appears to be in the WebP format. ImageIO does not support this format natively, so you will need a library like webp-imageio .

Install that library and see if your code works. ImageIO should automatically find the plugin when you run ImageIO.scanForPlugins() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM