将favicon检索为图标而不是图像

时间:2012-02-01 22:58:21

标签: c# image browser icons favicon

我使用了我发现的here的favicon代码来检索浏览器元素中加载的网站的favicon。

我想将此图标用作我的Windows窗体的图标。

感谢JP Hellemons此代码有效:

private void browser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) {
    this.Icon = favicon(GetActiveBrowser().Url);
}

private WebBrowser GetActiveBrowser() {
    return (WebBrowser)tabs.SelectedTab.Controls[0];
}

private Icon favicon(Uri url) {
    WebRequest request = (HttpWebRequest)WebRequest.Create("http://" + url.Host + "/favicon.ico");

    Bitmap bm = new Bitmap(32, 32);
    MemoryStream memStream;

    using (Stream response = request.GetResponse().GetResponseStream()) {
        memStream = new MemoryStream();
        byte[] buffer = new byte[1024];
        int byteCount;

        do {
            byteCount = response.Read(buffer, 0, buffer.Length);
            memStream.Write(buffer, 0, byteCount);
        } while (byteCount > 0);
    }

    bm = new Bitmap(Image.FromStream(memStream));

    if (bm != null) {
        Icon ic = Icon.FromHandle(bm.GetHicon());
        return ic;
    } else
        return Properties.Resources.GZbrowser;
}

2 个答案:

答案 0 :(得分:4)

根据此文档,它应该从流中工作。 http://msdn.microsoft.com/en-us/library/system.drawing.icon.aspx

我使用过这篇文章:http://odetocode.com/Blogs/scott/archive/2004/10/05/webrequest-and-binary-data.aspx

WebRequest request = (HttpWebRequest)WebRequest.Create("http://" + url.Host + "/favicon.ico");
Icon ic = new Icon(); // put default here
Bitmap bm = new Bitmap();

try
{
    using(WebResponse response = request.GetResponse())
    {
       using(Stream responseStream = response.GetResponseStream())
       {
          using(MemoryStream ms = new MemoryStream())
          {
              var tmp = Image.FromStream(ms); // changed bitmap to image
              bm = new Bitmap(tmp);
          }
       }
    }
}catch{}
if(bm != null)
{
    ic = Icon.FromHandle(bm.GetHicon);  
}
return ic;

编辑:这样的事情应该做到

Edit2:改变了答案中的一些内容。你能试试吗?

最终修改:(笑)

刚刚在Windows窗体应用程序中对此进行了测试,这是有效的! :)

Uri url = new Uri("http://www.google.nl");
WebRequest request = (HttpWebRequest)WebRequest.Create("http://" + url.Host + "/favicon.ico");

Bitmap bm = new Bitmap(32,32); 
MemoryStream memStream;

using (Stream response = request.GetResponse().GetResponseStream())
{
    memStream = new MemoryStream();
    byte[] buffer = new byte[1024];
    int byteCount;

    do
    {
        byteCount = response.Read(buffer, 0, buffer.Length);
        memStream.Write(buffer, 0, byteCount);
    } while (byteCount > 0);
}

bm = new Bitmap(Image.FromStream(memStream));                 

if (bm != null) 
{
    Icon ic = Icon.FromHandle(bm.GetHicon());
    this.Icon = ic;
}

答案 1 :(得分:0)

首先读取响应字节数组,然后创建它的MemoryStream并从该MemoryStream创建图标。

网络流不支持创建图标所需的搜索操作。