我有一个带有URL的字符串。例如"http://google.com“。
有没有办法把这个页面下载并渲染成图片文件?("test.jpg")
我试图使用WebBrowser控件来下载和渲染图片,但它只在WebBrowser以显示的形式放置时才起作用。在其他方面,它只渲染黑色矩形。
但是我想渲染没有任何视觉效果的图片(创建,激活表单等)。
发布于 2010-04-05 21:48:17
Internet Explorer支持IHtmlElementRenderer接口,该接口可用于将页面呈现到任意设备上下文。下面是一个示例表单,向您展示如何使用它。从项目+添加引用开始,选择Microsoft.mshtml
using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace WindowsFormsApplication1 {
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
webBrowser1.Url = new Uri("http://stackoverflow.com");
webBrowser1.DocumentCompleted += webBrowser1_DocumentCompleted;
}
void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) {
if (!e.Url.Equals(webBrowser1.Url)) return;
// Get the renderer for the document body
mshtml.IHTMLDocument2 doc = (mshtml.IHTMLDocument2)webBrowser1.Document.DomDocument;
mshtml.IHTMLElement body = (mshtml.IHTMLElement)doc.body;
IHTMLElementRender render = (IHTMLElementRender)body;
// Render to bitmap
using (Bitmap bmp = new Bitmap(webBrowser1.ClientSize.Width, webBrowser1.ClientSize.Height)) {
using (Graphics gr = Graphics.FromImage(bmp)) {
IntPtr hdc = gr.GetHdc();
render.DrawToDC(hdc);
gr.ReleaseHdc();
}
bmp.Save("test.png");
System.Diagnostics.Process.Start("test.png");
}
}
// Replacement for mshtml imported interface, Tlbimp.exe generates wrong signatures
[ComImport, InterfaceType((short)1), Guid("3050F669-98B5-11CF-BB82-00AA00BDCE0B")]
private interface IHTMLElementRender {
void DrawToDC(IntPtr hdc);
void SetDocumentPrinter(string bstrPrinterName, IntPtr hdc);
}
}
}发布于 2011-12-27 13:52:06
不幸的是,MS不推荐在IE 9中使用IHtmlElementRenderer::DrawToDC()。http://msdn.microsoft.com/en-us/library/aa752273(v=vs.85).aspx
https://stackoverflow.com/questions/2578190
复制相似问题