网页快照

C#生成网站网页快照,Html转成图片
2012-04-09 22:29

HtmlToImg.cs

 

using System;

using System.Drawing;

using System.Threading;

using System.Windows.Forms;

/// <summary>

/// 生成网页快照

/// </summary>

publicclassHtmlToImg

{

    Bitmap m_Bitmap;

    string m_Url;

    int m_BrowserWidth, m_BrowserHeight, m_ThumbnailWidth, m_ThumbnailHeight;

    public HtmlToImg(string Url, int BrowserWidth, int BrowserHeight, int ThumbnailWidth, int ThumbnailHeight)

    {

        m_Url = Url;

        m_BrowserHeight = BrowserHeight;

        m_BrowserWidth = BrowserWidth;

        m_ThumbnailWidth = ThumbnailWidth;

        m_ThumbnailHeight = ThumbnailHeight;

    }

    publicstaticBitmap GetHtmlToImg(string Url, int BrowserWidth, int BrowserHeight, int ThumbnailWidth, int ThumbnailHeight)

    {

        HtmlToImg thumbnailGenerator = newHtmlToImg(Url, BrowserWidth, BrowserHeight, ThumbnailWidth, ThumbnailHeight);

        return thumbnailGenerator.GenerateHtmlToImgImage();

    }

    publicBitmap GenerateHtmlToImgImage()

    {

        Thread m_thread = newThread(newThreadStart(_GenerateHtmlToImgImage));

        m_thread.SetApartmentState(ApartmentState.STA);

        m_thread.Start();

        m_thread.Join();

        return m_Bitmap;

    }

    privatevoid _GenerateHtmlToImgImage()

    {

        WebBrowser m_WebBrowser = newWebBrowser();

        m_WebBrowser.ScrollBarsEnabled = false;

        m_WebBrowser.Navigate(m_Url);

        m_WebBrowser.DocumentCompleted += newWebBrowserDocumentCompletedEventHandler(WebBrowser_DocumentCompleted);

        while (m_WebBrowser.ReadyState != WebBrowserReadyState.Complete)

            Application.DoEvents();

搜企业(www.soqiye.cn)

        m_WebBrowser.Dispose();

    }

    privatevoid WebBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)

    {

        WebBrowser m_WebBrowser = (WebBrowser)sender;

        m_WebBrowser.ClientSize = newSize(this.m_BrowserWidth, this.m_BrowserHeight);

        m_WebBrowser.ScrollBarsEnabled = false;

        m_Bitmap = newBitmap(m_WebBrowser.Bounds.Width, m_WebBrowser.Bounds.Height);

        m_WebBrowser.BringToFront();

        m_WebBrowser.DrawToBitmap(m_Bitmap, m_WebBrowser.Bounds);

        m_Bitmap = (Bitmap)m_Bitmap.GetThumbnailImage(m_ThumbnailWidth, m_ThumbnailHeight, null, IntPtr.Zero);

    }

}

 

 

 

调用方法:

         Bitmap bmp = HtmlToImg.GetHtmlToImg("http://www.baidu.com/", 800, 600, 800, 600);

        MemoryStream stream = newMemoryStream();

        bmp.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);

        byte[] buff = stream.ToArray();

 

        //直接显示图片

        //Response.ContentType = "image/Jpeg";

        //Response.BinaryWrite(buff);

        //Response.End();

 

        //保存图片

        FileStream fs = newFileStream(Server.MapPath(DateTime.Now.Date.ToShortDateString() + ".jpg"), FileMode.Create);

        stream.WriteTo(fs);

        stream.Close();

        fs.Close();

你可能感兴趣的:(网页)