nick zoum
nick zoum

Reputation: 7315

How do i read the favicon of an webpage in Java?

I want to find a way to read the favicon of a webpage and pass it to an Image in my program. So far I've created these methods that read the webpage, find the line favicon (or the first .ico file) and then isolate the url. Finally i read the image from that url.

public static Image getFavIcon(String path) {
    try {
        URL url = new URL(path);
        BufferedReader input = new BufferedReader(new InputStreamReader(url.openStream()));
        String temp;
        while ((temp = input.readLine()) != null) {
            if (temp.toLowerCase().contains(("favicon").toLowerCase())) {
                break;
            }
            if (temp.toLowerCase().contains((".ico").toLowerCase())) {
                break;
            }
        }
        return getFavIcon(getURL(temp));
    } catch (IOException e) {
        return null;
    }
}

public static URL getURL(String input) throws MalformedURLException {
    for (int index = 0; index < input.length(); index++) {
        try {
            if (input.substring(index, index + 4).equals("href")) {
                String temp = getString(input.substring(index));
                if (temp != null) {
                    return new URL(temp);
                }
            }
        } catch (StringIndexOutOfBoundsException e) {

        }
    }
    return null;
}

public static String getString(String input) throws StringIndexOutOfBoundsException {
    int first = -1;
    int second = -1;
    int index = 0;
    while ((first == -1) || (second == -1)) {
        if (input.charAt(index) == 34) {
            if (first == -1) {
                first = index;
            } else {
                second = index;
            }
        }
        index++;
    }
    String temp = input.substring(first + 1, second);
    int length = temp.length();
    if (temp.substring(length - 4).equals(".ico")) {
        return temp;
    }
    return null;
}

public static Image getFavIcon(URL url) {
    return java.awt.Toolkit.getDefaultToolkit().createImage(url);
}

The problem is that the image returned by getFavicon though not null is either empty, invisible or not opaque. When i try to print it g.drawImage() or g2.drawImage() its empty but it does not throw a null Pointer exception

I tried the library described here but i was not sure how to read the icon from the url. So does anybody know how to read the icon from the url or a simpler way to get the favicon to the image?

Upvotes: 0

Views: 953

Answers (1)

Nishu Tayal
Nishu Tayal

Reputation: 20860

You can use JsonP library to get the favicon.

Lets say, favicon is defined in the following way:

  <head>
    <link rel="icon" href="http://example.com/image.ico" />
  </head>

You can use following code:

Element element = doc.head().select("link[href~=.*\\.(ico|png)]").first();
System.out.println(element.attr("href"));

Here is the example.

Upvotes: 2

Related Questions