java - 如何在 Java 中读取网页的图标?

标签 java image url icons favicon

我想找到一种方法来读取网页的图标并将其传递给我的程序中的图像。到目前为止,我已经创建了这些方法来读取网页,找到该行图标(或第一个 .ico 文件),然后隔离 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);
}

问题是 getFavicon 返回的图像虽然不为 null,但它要么是空的、不可见的,要么不是不透明的。当我尝试打印它时 g.drawImage() 或 g2.drawImage() 它是空的,但它不会抛出空指针异常

我尝试了描述的库 here 但我不知道如何从网址读取图标。 那么有人知道如何从网址读取图标或者更简单的方法将图标获取到图像吗?

最佳答案

您可以使用 JsonP 库来获取图标。

可以说,favicon 的定义方式如下:

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

您可以使用以下代码:

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

这是example .

关于java - 如何在 Java 中读取网页的图标?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37102243/

相关文章:

image - 是否可以在 Sprite 图像中重复背景条

android - 加载本地文件并得到未知的 Chrome 错误 : -6

html - 如何在使用图像类型按钮以 HTML 表单提交时删除 x 和 y?

java - 安卓 : Get fragment's background color

Java 自绑定(bind)泛型

php - 将图像转换为字符串(用于 Symfony2 响应)

html - Flex、图片和滚动位置

java - org.postgresql.util.PSQLException : Unable to interpret the update count in command completion tag

java - 当路径和文件名都包含通配符时列出与正则表达式匹配的文件路径

javascript - 组合书签以在两个 URL 之间创建切换