0

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 BufferedImage. Also, how can I make the above code block until the image is loaded? I know I can use an ImageObserver, but is there a simpler way?

When I try the second option, I get this exception:

javax.imageio.IIOException: Can't read input file!
Sildoreth
  • 1,883
  • 1
  • 25
  • 38
Savvas Dalkitsis
  • 11,476
  • 16
  • 65
  • 104

2 Answers2

3

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
  • 159,216
  • 35
  • 211
  • 226
  • :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 Jun 17 '09 at 14:39
1

File objects cant read from URLs

pauljwilliams
  • 19,079
  • 3
  • 51
  • 79
  • Although the solution has been posted, this is the real answer to the question. java.io.File can't read URLs. – Freddy Jun 17 '09 at 14:55
  • 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 Jun 18 '09 at 14:04