如何使用 Java 从网站获取 favicon.ico? [英] How to get favicon.ico from a website using Java?

查看:52
本文介绍了如何使用 Java 从网站获取 favicon.ico?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我正在制作一个应用程序来存储所有用户最喜欢的应用程序的快捷方式,就像一个集线器.我可以支持实际文件,并且我有一个用于快捷方式的 .lnk 解析器.我认为该应用程序也支持 Internet 快捷方式会非常好.这就是我正在做的:

So I'm making an application to store shortcuts to all the user's favorite applications, acting kind of like a hub. I can have support for actual files and I have a .lnk parser for shortcuts. I thought it would be pretty good for the application to support Internet shortcuts, too. This is what I'm doing:

假设我正在尝试获取 Google 的图标 (http://www.google.com/favicon.ico).

Suppose I'm trying to get Google's icon (http://www.google.com/favicon.ico).

  1. 我首先删除了多余的页面(例如 www.google.com/anotherpage 将变成 www.google.com.

然后,我使用 ImageIO.read(java.net.URL) 来获取图像.

Then, I use ImageIO.read(java.net.URL) to get the Image.

问题是当我调用这个方法时 ImageIO 从不返回图像:

The problem is that ImageIO never returns an Image when I call this method:

String trimmed = getBaseURL(page); //This removes the extra pages
Image icon = null;    
try {
    String fullURLString = trimmed + "/favicon.ico";
    URL faviconURL = new URL(fullURLString);
    icon = ImageIO.read(faviconURL);
} catch (IOException e) {
    e.printStackTrace();
}

return icon;

现在我有两个问题:

  1. Java 是否支持 ICO 格式,即使它来自 Microsoft?
  2. 为什么 ImageIO 无法从 URL 读取?
  1. Does Java support the ICO format even though it is from Microsoft?
  2. Why does ImageIO fail to read from the URL?

先谢谢你!

推荐答案

尝试 Image4J.

正如这个快速的 Scala REPL 会话所示(可粘贴为 Java 代码):

As this quick Scala REPL session shows (paste-able as Java code):

> net.sf.image4j.codec.ico.ICODecoder.read(new java.net.URL("http://www.google.com/favicon.ico").openStream())

res1: java.util.List[java.awt.image.BufferedImage] = [BufferedImage@65712a80: type = 2 DirectColorModel: rmask=ff0000 gmask=ff00 bmask=ff amask=ff000000 IntegerInterleavedRaster: width = 16 height = 16 #Bands = 4 xOff = 0 yOff = 0 dataOffset[0] 0]

<小时>

更新

回答您的问题:Java 是否支持 ICO?好像不是:

To answer your questions: Does Java support ICO? Doesn't seem like it:

> javax.imageio.ImageIO.read(new java.net.URL("http://www.google.com/favicon.ico"))

java.lang.IllegalArgumentException: Empty region!

为什么 ImageIO 无法从 URL 中读取?好吧,URL 本身似乎对我有用,所以您可能有代理/防火墙问题,或者可能是上述问题.

Why does ImageIO fail to read from the URL? Well, the URL itself seems to work for me, so you may have a proxy/firewall issue, or it could be the problem above.

这篇关于如何使用 Java 从网站获取 favicon.ico?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆