/*
 * 修改者:吴鹏(AlphaWu)
 * Blog:Http://AlphaWu.CoM
 * 获取网站缩略图代码
 * 2006 圣诞节
 * C#代码根据该页面“http://www.codeproject.com/useritems/website_screenshot.asp”
 * VB.Net代码修改而来
 * 欢迎修改和传播
 * 最好能保留该信息^_^
 * 也欢迎大家访问我的博客
 * Http://AlphaWu.Cnblogs.CoM
 * 
 * Http://AlphaWu.CoM
 * 
 * 
 */
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Windows.Forms;namespace Snap
{
    public class GetImage
    {
        int S_Height;
        int S_Width;
        int F_Height;
        int F_Width;
        string MyURL;        public int ScreenHeight
        {
            get
            {
                return S_Height;
            }
            set
            {
                S_Height = value;
            }
        }        public int ScreenWidth
        {
            get
            {
                return S_Width;
            }
            set
            {
                S_Width = value;
            }
        }        public int ImageHeight
        {
            get
            {
                return F_Height;
            }
            set
            {
                F_Height = value;
            }
        }        public int ImageWidth
        {
            get
            {
                return F_Width;
            }
            set
            {
                F_Width = value;
            }
        }        public string WebSite
        {
            get
            {
                return MyURL;
            }
            set
            {
                MyURL = value;
            }
        }        public GetImage(string WebSite, int ScreenWidth, int ScreenHeight, int ImageWidth, int ImageHeight)
        {
            this.WebSite = WebSite;
            this.ScreenHeight = ScreenHeight;
            this.ScreenWidth = ScreenWidth;
            this.ImageHeight = ImageHeight;
            this.ImageWidth = ImageWidth;
        }        public  Bitmap GetBitmap()
        {
            WebPageBitmap Shot = new WebPageBitmap(this.WebSite, this.ScreenWidth, this.ScreenHeight);            Shot.GetIt();
            Bitmap Pic = Shot.DrawBitmap(this.ImageHeight, this.ImageWidth);
            return Pic;
        }
    }    public class WebPageBitmap
    {
        WebBrowser MyBrowser;
        string URL;
        int Height;
        int Width;        public  WebPageBitmap(string url, int width, int height)
        {
            this.URL = url;
            this.Width = width;
            this.Height = height;
            MyBrowser = new WebBrowser();
            MyBrowser.ScrollBarsEnabled = false;
            MyBrowser.Size = new Size(this.Width, this.Height);
        }        public void GetIt()
        {
            MyBrowser.Navigate(this.URL);
            while (MyBrowser.ReadyState != WebBrowserReadyState.Complete)
            {
                Application.DoEvents();
            }
        }        public Bitmap DrawBitmap(int theight, int twidth)
        {
            Bitmap myBitmap = new Bitmap(this.Width, this.Height);
            Rectangle DrawRect = new Rectangle(0, 0, this.Width, this.Height);
            MyBrowser.DrawToBitmap(myBitmap, DrawRect);
            System.Drawing.Image imgOutput = myBitmap;
            System.Drawing.Bitmap oThumbNail = new Bitmap(twidth, theight, imgOutput.PixelFormat);
            Graphics g = Graphics.FromImage(oThumbNail);            g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighSpeed;
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighSpeed;
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBilinear;            Rectangle oRectangle = new Rectangle(0, 0, twidth, theight);
            g.DrawImage(imgOutput, oRectangle);            try
            {
                return oThumbNail;
            }
            catch
            {
                return null;
            }
            finally
            {
                imgOutput.Dispose();
                imgOutput = null;
                MyBrowser.Dispose();
                MyBrowser = null;
            }        }
    }
}
下面是调用代码:
            string url = string.Empty;
            url = Request.QueryString[0];
            try
            {
                GetImage thumb = new GetImage(url, 1024, 768, 320, 240);
                System.Drawing.Bitmap x = thumb.GetBitmap();
                x.Save(Response.OutputStream, ImageFormat.Jpeg);
                Response.ContentType = "image/jpeg";
            }
            catch
            {
                
            }       
有的站截出来的图是空白的.不知道是哪里问题.谁来解决一下,谢谢.
目前发现是空白的站有:
http://m.iask.com/
http://mp3.sogou.com/

解决方案 »

  1.   

    我知道了,你的代码是必须要知道具体的页面,比如http://www.yahoo.com.cn/不行,必须是http://www.aa.con/aa.aspx,这样子的
      

  2.   

    代码太多...不过
     x.Save(Response.OutputStream, ImageFormat.Jpeg);
                    Response.ContentType = "image/jpeg";
    这两个顺序要倒一下吧
      

  3.   

    试了下,楼主的代码用了WebBrowser控件,这个东西web使用麻烦啊,必须在单线程使用
      

  4.   


    不用的,比如www.baidu.com和www.qq.com都是可以的.
      

  5.   

    不说了,代码说话
    改后的是
    using System.Windows.Forms;
    using System.Drawing;
    using System.Net;
    using mshtml;
    using System.Reflection;
    using System.Runtime.InteropServices;
    using System;
    using System.Drawing.Drawing2D;
      

  6.   

    代码说话
    using System.Windows.Forms;
    using System.Drawing;
    using System.Net;
    using mshtml;
    using System.Reflection;
    using System.Runtime.InteropServices;
    using System;
    using System.Drawing.Drawing2D;namespace WebImage
    {
        [InterfaceType(1)]
        [Guid("3050F669-98B5-11CF-BB82-00AA00BDCE0B")]
        public interface IHTMLElementRender2
        {
            void DrawToDC(IntPtr hdc);
            void SetDocumentPrinter(string bstrPrinterName, ref _RemotableHandle hdc);
        }    public class GetImage
        {
            private string MyURL;
            private int Browser_Height;
            private int Browser_Width;
            private int Img_Height;
            private int Img_Width;        public int BrowserHeight
            {
                get
                {
                    return Browser_Height;
                }
                set
                {
                    Browser_Height = value;
                }
            }        public int BrowserWidth
            {
                get
                {
                    return Browser_Width;
                }
                set
                {
                    Browser_Width = value;
                }
            }        public int ImageHeight
            {
                get
                {
                    return Img_Height;
                }
                set
                {
                    Img_Height = value;
                }
            }        public int ImageWidth
            {
                get
                {
                    return Img_Width;
                }
                set
                {
                    Img_Width = value;
                }
            }        public string WebUrl
            {
                get
                {
                    return MyURL;
                }
                set
                {
                    MyURL = value;
                }
            }        /// <summary>
            /// 主要是得到参数
            /// </summary>
            /// <param name="WebSite"></param>
            /// <param name="ScreenWidth"></param>
            /// <param name="ScreenHeight"></param>
            /// <param name="ImageWidth"></param>
            /// <param name="ImageHeight"></param>
            public GetImage(string WebSite, int ScreenWidth, int ScreenHeight, int ImageWidth, int ImageHeight)
            {
                this.WebUrl = WebSite;
                this.BrowserHeight = ScreenHeight;
                this.BrowserWidth = ScreenWidth;
                this.ImageHeight = ImageHeight;
                this.ImageWidth = ImageWidth;
            }        public Bitmap GetBitmap()
            {
                WebPageBitmap Shot = new WebPageBitmap(this.WebUrl, this.BrowserWidth, this.BrowserHeight);
                if (Shot.IsOk)
                {
                    Shot.GetImg();
                    Bitmap Pic = Shot.DrawBitmap(this.ImageHeight, this.ImageWidth);
                    return Pic;
                }
                else
                {
                    MessageBox.Show(Shot.ErrorMessage);
                }            return new Bitmap(100, 100);
            }
        }
      

  7.   

     public class WebPageBitmap
        {
            private WebBrowser webBrowser;
            private string URL;
            private int Height;
            private int Width;
            private bool isOk;
            private string errorMessage;        public string ErrorMessage
            {
                get { return errorMessage; }
            }        public bool IsOk
            {
                get { return isOk; }
                set { isOk = value; }
            }        public WebPageBitmap(string url, int width, int height)
            {
                this.Width = width;
                this.Height = height;            this.URL =
                    url.StartsWith("http://", StringComparison.InvariantCultureIgnoreCase) ?
                    url : this.URL = "http://" + url;            try
                // needed as the script throws an exeception if the host is not found
                {
                    HttpWebRequest req = (HttpWebRequest)WebRequest.Create(this.URL);
                    req.AllowAutoRedirect = true;
                    req.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; SLCC1; .NET CLR 2.0.50727; .NET CLR 3.0.04506; .NET CLR 3.5.21022; .NET CLR 1.0.3705; .NET CLR 1.1.4322)";
                    //req.Referer = "http://www.cognifide.com"; //这一句应该是告诉服务器我是从哪个页面链接过来的
                    req.ContentType = "text/html";
                    req.Accept = "*/*";
                    req.KeepAlive = false;                using (HttpWebResponse resp = (HttpWebResponse)req.GetResponse())
                    {
                        string x = resp.StatusDescription;
                    }            }
                catch (Exception ex)
                {
                    errorMessage = ex.Message;
                    isOk = false;
                    return;
                }
                isOk = true;    
             // public, to check in program.cs if the domain is found, so the image can be saved            webBrowser = new WebBrowser();
                webBrowser.Size = new Size(this.Width, this.Height);
                webBrowser.ScrollBarsEnabled = false;
                webBrowser.DocumentCompleted +=
                new WebBrowserDocumentCompletedEventHandler(documentCompletedEventHandler);        }        /// <summary>
            /// Fetches the image 
            /// </summary>
            /// <returns>true is the operation ended with a success</returns>
            public bool GetImg()
            {
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(URL);
                req.AllowAutoRedirect = true;
                req.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; SLCC1; .NET CLR 2.0.50727; .NET CLR 3.0.04506; .NET CLR 3.5.21022; .NET CLR 1.0.3705; .NET CLR 1.1.4322)";
                // req.Referer = "http://www.cognifide.com";//同上面的注释
                req.ContentType = "text/html";
                req.AllowWriteStreamBuffering = true;
                req.AutomaticDecompression = DecompressionMethods.GZip;
                req.Method = "GET";
                req.Proxy = null;
                req.ReadWriteTimeout = 20;            HttpStatusCode status;
                using (HttpWebResponse resp = (HttpWebResponse)req.GetResponse())
                {
                    status = resp.StatusCode;
                }            if (status == HttpStatusCode.OK || status == HttpStatusCode.Moved)
                {
                    webBrowser.Navigate(URL);
                    while (webBrowser.ReadyState != WebBrowserReadyState.Complete)
                    {
                        Application.DoEvents();                }
                    return true;
                }
                else
                {
                    return false;
                }
            }        private void documentCompletedEventHandler(object sender, WebBrowserDocumentCompletedEventArgs e)
            {
                ((WebBrowser)sender).Document.Window.Error +=
                    new HtmlElementErrorEventHandler(SuppressScriptErrorsHandler);
            }        public void SuppressScriptErrorsHandler(object sender, HtmlElementErrorEventArgs e)
            {
                e.Handled = true;
                MessageBox.Show("Error!");
            }        internal Bitmap DrawBitmap(int thumbwidth, int thumbheight)
            {
                
                IHTMLDocument2 rawDoc = (IHTMLDocument2)webBrowser.Document.DomDocument;
                IHTMLElement rawBody = rawDoc.body;
                IHTMLElementRender2 render = (IHTMLElementRender2)rawBody;            Bitmap bitmap = new Bitmap(Width, Height);
                Rectangle bitmapRect = new Rectangle(0, 0, Width, Height);            // Interesting thing that despite using the renderer later 
                // this following line is still necessary or 
                // the background may not be painted on some websites.
                webBrowser.DrawToBitmap(bitmap, bitmapRect);            using (Graphics graphics = Graphics.FromImage(bitmap))
                {
                    IntPtr graphicshdc = graphics.GetHdc();
                    render.DrawToDC(graphicshdc);                graphics.ReleaseHdc(graphicshdc);
                    graphics.Dispose();                if (thumbheight == Height && thumbwidth == Width)
                    {
                        return bitmap;
                    }
                    else
                    {
                        Bitmap thumbnail = new Bitmap(thumbwidth, thumbheight);
                        using (Graphics gfx = Graphics.FromImage(thumbnail))
                        {
                            // high quality image sizing
                            gfx.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                            gfx.InterpolationMode = InterpolationMode.HighQualityBicubic;                                                                       // make it look pretty 
                            gfx.DrawImage(bitmap, new Rectangle(0, 0, thumbwidth, thumbheight), bitmapRect, GraphicsUnit.Pixel);
                        }
                        bitmap.Dispose();
                        return thumbnail;
                    }
                }
            }
        }
    }
    这是改成你上面风格的代码
      

  8.   

    原文地址http://www.codeproject.com/KB/cs/Website_Thumbnails_in_C.aspxHow To Get A Website Thumbnail in a C# Application Without Creating A Form (console)

    昨天看到你发这个,觉得很有意思,就看了一下,只是看了别人的代码,不好意思,只能给你提供地址,一起研究