如何从Java中读取URL中的图像?

时间:2010-10-21 11:24:50

标签: java image

我的web应用程序中有servlet提供图像,当我访问那些带有浏览器图像的URL时,服务器是正确的。然后我有另一个调整图像大小的servlet,想法是在resize servlet中通过url访问get图像,然后调整图像大小。但由于某种原因,以下所有方法都返回null,但是当我使用浏览器访问给定的URL时,图像显示正确。

    URL imageURL = new URL(fullUrl);
    // Case 1
    RenderedImage img = ImageIO.read(imageURL);

    // Case 2
    BufferedImage img = JAI.create("url", imageURL).getAsBufferedImage();

    // Case 3
    Image img = java.awt.Toolkit.getDefaultToolkit().getDefaultToolkit().createImage(imageURL);

3 个答案:

答案 0 :(得分:22)

URL url = new URL("http://www.digitalphotoartistry.com/rose1.jpg");
Image image = ImageIO.read(url);  

URL url = new URL("http://www.digitalphotoartistry.com/rose1.jpg");
java.awt.Image image = java.awt.Toolkit.getDefaultToolkit().createImage(url);   

更新:

此代码适用于我 请尝试检查您的网址。

public static void main(String[] args) throws Exception {
   URL imageURL = new URL("http://www.digitalphotoartistry.com/rose1.jpg");
    // Case 1
    RenderedImage img = ImageIO.read(imageURL);
    System.out.println(img);
}

输出:

BufferedImage@e80a59: type = 5 ColorModel: #pixelBits = 24 numComponents = 3 col
or space = java.awt.color.ICC_ColorSpace@1ff5ea7 transparency = 1 has alpha = fa
lse isAlphaPre = false ByteInterleavedRaster: width = 553 height = 737 #numDataE
lements 3 dataOff[0] = 2

答案 1 :(得分:0)

来自the docs

  

如果没有已注册ImageReader声明能够阅读结果流,则会返回null

可能是您没有注册ImageReader图片类型吗?

答案 2 :(得分:0)

显示从JFrame中的URL读取的图像。 urlLocation指向图片的URL。

public class ShowImageFromURL {

    public static void show(String urlLocation) {
        Image image = null;
        try {
            URL url = new URL(urlLocation);
            URLConnection conn = url.openConnection();
            conn.setRequestProperty("User-Agent", "Mozilla/5.0");

            conn.connect();
            InputStream urlStream = conn.getInputStream();
            image = ImageIO.read(urlStream);

            JFrame frame = new JFrame();
            JLabel lblimage = new JLabel(new ImageIcon(image));
            frame.getContentPane().add(lblimage, BorderLayout.CENTER);
            frame.setSize(image.getWidth(null) + 50, image.getHeight(null) + 50);
            frame.setVisible(true);

        } catch (IOException e) {
            System.out.println("Something went wrong, sorry:" + e.toString());
            e.printStackTrace();
        }
    }
}

参考:https://gist.github.com/aslamanver/92af3ac67406cfd116b7e4e177156926