Skip to content

Instantly share code, notes, and snippets.

@borgle
Created June 17, 2013 07:11
Show Gist options
  • Save borgle/5795121 to your computer and use it in GitHub Desktop.
Save borgle/5795121 to your computer and use it in GitHub Desktop.
根据html代码利用WebBrowser控件生成图片功能。 可以利用此代码完成长微博的发布。
namespace Utils
{
/*
Bitmap bitmap = Utils.Html2Image.GenerateImage("<h1>标题一</h1><h2>标题二</h2><font color=\"red\">红色普通</font><br /><img src=\"https://www.google.com/images/srpr/logo4w.png\" />", 440);
//MemoryStream ms = new MemoryStream();
//bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Png);//JPG、GIF、PNG等均可
bitmap.Save(Server.MapPath("img.png"), System.Drawing.Imaging.ImageFormat.Png);
*/
using System;
using System.Drawing;
using System.Threading;
using System.Windows.Forms;
public class Html2Image
{
Bitmap _Bitmap;
string _txtHtml;
int _BrowserWidth, _BrowserHeight, _ThumbnailWidth, _ThumbnailHeight;
public Html2Image(string txtHtml, int maxWidth)
{
_txtHtml = txtHtml;
_ThumbnailWidth = maxWidth;
}
public static Bitmap GenerateImage(string txtHtml, int maxWidth)
{
Html2Image thumbnailGenerator = new Html2Image(txtHtml, maxWidth);
return thumbnailGenerator.CreateThumbnailImage();
}
public Bitmap CreateThumbnailImage()
{
Thread thd = new Thread(new ThreadStart(_GenerateThumbnailImage));
thd.SetApartmentState(ApartmentState.STA);
thd.Start();
thd.Join();
return _Bitmap;
}
private void _GenerateThumbnailImage()
{
WebBrowser Browser = new WebBrowser();
Browser.ScrollBarsEnabled = false;
Browser.DocumentText = _txtHtml;
Browser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(WebBrowser_DocumentCompleted);
while (Browser.ReadyState != WebBrowserReadyState.Complete)
{
Application.DoEvents();
}
Browser.Dispose();
}
private void WebBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
WebBrowser Browser = (WebBrowser)sender;
HtmlDocument hd = Browser.Document;
int height = Convert.ToInt32(hd.Body.GetAttribute("scrollHeight")) + 10;
int width = Convert.ToInt32(hd.Body.GetAttribute("scrollWidth")) + 10;
this._BrowserHeight = height;
this._BrowserWidth = width;
//如果html的内容区域大于设定的图片大小,则缩略
if (width <= _ThumbnailWidth) { _ThumbnailWidth = width; }
_ThumbnailHeight = height * _ThumbnailWidth / width;
Browser.ClientSize = new Size(this._BrowserWidth, this._BrowserHeight);
Browser.ScrollBarsEnabled = false;
_Bitmap = new Bitmap(_ThumbnailWidth, _ThumbnailHeight);
Graphics g = Graphics.FromImage(_Bitmap);
g.Clear(Color.White);
Browser.BringToFront();
Browser.DrawToBitmap(_Bitmap, Browser.Bounds);
_Bitmap = (Bitmap)_Bitmap.GetThumbnailImage(_ThumbnailWidth, _ThumbnailHeight, null, IntPtr.Zero);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment