[英]How do i read the favicon of an webpage in Java?
我想找到一種方法來讀取網頁的圖標並將其傳遞給程序中的圖像。 到目前為止,我已經創建了這些方法來讀取網頁,找到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()時,它為空,但不會拋出null指針異常
我嘗試了此處描述的庫,但不確定如何從URL中讀取圖標。 那么,有人知道如何從url讀取圖標,或者更簡單的方法將favicon獲取到圖像嗎?
您可以使用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"));
這是例子 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.