tags:

views:

553

answers:

2

Hi i am trying to read an image that resides somewhere on the web from my Java program. So far i have successfully loaded an image by using the following code.

URL url = new URL("http://www.google.com/images/nav_logo4.png");
Image img = Toolkit.getDefaultToolkit().getImage(url);

What i want to know is why this code (which is the first i tried) does not work :

BufferedImage img = ImageIO.read(new File("http://www.google.com/images/nav_logo4.png));

This would have the benefit of giving me a Buffered image. Also how can i make the above code block until the image is loaded. I know i can use an image observer but is there a simpler way?

When i try the second option i get this exception :

javax.imageio.IIOException: Can't read input file!
+1  A: 

A File cannot refer to a URL.

Although I haven't tried it, there appears to be a ImageIO.read(URL) method, which can take an URL as the input as an URL object.

I would presume it would be called as follows:

ImageIO.read(new URL("http://url/to/my/image.png"));
coobird
:D i was just about to mark this question as answered since i found the solution you proposed on my own just now. Thank you anyway your answer was correct.
Savvas Dalkitsis
Good to hear that the solution works :)
coobird
+2  A: 

File objects cant read from URLs

Visage
Although the solution has been posted, this is the real answer to the question. java.io.File can't read URLs.
Freddy
you are correct. I know i should promote this answer since it responds to my question. I chose the other one though because it offered a solution as well :D I should have rephrased the question i guess...
Savvas Dalkitsis