Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I read image from URL in Java?

Tags:

java

image

I have servlet in my web application that serves images, and when I visit those urls with browser images are server correctly. Then I have this other servlet that resizes images, idea is to visit get image by url in resize servlet and then resize image. But for some reason all following methods return null, but when I visit given url with browser, image is shown correctly.

    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);
like image 589
newbie Avatar asked Oct 21 '10 11:10

newbie


1 Answers

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

or

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

Update:

This code works for me Try checking your 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);
}

output:

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
like image 92
jmj Avatar answered Sep 18 '22 07:09

jmj