Take the 2-minute tour ×

I'm trying to get an image off the internet from an URL in java. I'm using the following code.

URL url = new URL(webAddress);
image = ImageIO.read(url);

Sometimes it works and sometimes it just hangs indefinitely, depending on what WebAddress is. No error message, it just keeps running and doing nothing.

There are definitely images at the addresses where it hangs forever, as confirmed by copying and pasting them into a web browser. There appears to be no pattern to which ones work and which ones don't- they're all jpegs. I've done some searching and found some other methods for getting an image from an URL, but the same thing happens with all of them- they work on some images and hang on others.

Do you have any idea what could be causing this, and how to fix it?

share|improve this question
Can you give an example URL on which it hangs? –  npe Jun 15 '12 at 19:13
add comment

1 Answer

up vote 2 down vote accepted

Hmm I'm not sure try this and see if any change or error is thrown. I also think maybe you have setRedirects(boolean b) to false this also maybe giving problems but try this first:

    try {
        String webadd="urls go here try the two you have had probelms with and success";
        URL url = new URL(webadd);

        URLConnection con = url.openConnection();
        InputStream in = con.getInputStream();
        Image img = ImageIO.read(in);
        if (img != null) {
        } else {
            System.out.println("Could not load");

    } catch (IOException ex) {

EDIT: or maybe a bug?: http://bugs.sun.com/view_bug.do;jsessionid=2bc7386e2f8b4e2550f8b10122f?bug_id=6309072 to check this if the error still occurs with the above code try:

        Image img=new ImageIcon(url).getImage();
share|improve this answer
The ImageIcon technique worked. Thanks. –  Bergil Jun 15 '12 at 19:55
Hmmm so it might just be a bug? well glad you got it working i've got into the habit of ImageIcon().getImage() so never had trouble. –  David Kroukamp Jun 15 '12 at 20:00
add comment

Your Answer


