欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

c#根据网址抓取网页截屏生成图片的示例

程序员文章站 2024-02-18 08:08:58
复制代码 代码如下:using system.drawing;using system.drawing.imaging;using system.io;using syst...

复制代码 代码如下:

using system.drawing;
using system.drawing.imaging;
using system.io;
using system.threading;
using system.windows.forms;

public class websitetoimage
{
private bitmap m_bitmap;
private string m_url;
private string m_filename = string.empty;

public websitetoimage(string url)
{
// without file
m_url = url;
}

public websitetoimage(string url, string filename)
{
// with file
m_url = url;
m_filename = filename;
}

public bitmap generate()
{
// thread
var m_thread = new thread(_generate);
m_thread.setapartmentstate(apartmentstate.sta);
m_thread.start();
m_thread.join();
return m_bitmap;
}

private void _generate()
{
var browser = new webbrowser { scrollbarsenabled = false };
browser.navigate(m_url);
browser.documentcompleted += webbrowser_documentcompleted;

while (browser.readystate != webbrowserreadystate.complete)
{
application.doevents();
}

browser.dispose();
}

private void webbrowser_documentcompleted(object sender, webbrowserdocumentcompletedeventargs e)
{
// capture
var browser = (webbrowser)sender;
browser.clientsize = new size(browser.document.body.scrollrectangle.width, browser.document.body.scrollrectangle.bottom);
browser.scrollbarsenabled = false;
m_bitmap = new bitmap(browser.document.body.scrollrectangle.width, browser.document.body.scrollrectangle.bottom);
browser.bringtofront();
browser.drawtobitmap(m_bitmap, browser.bounds);

// save as file?
if (m_filename.length > 0)
{
// save
m_bitmap.savejpg100(m_filename);
}
}
}

public static class bitmapextensions
{
public static void savejpg100(this bitmap bmp, string filename)
{
var encoderparameters = new encoderparameters(1);
encoderparameters.param[0] = new encoderparameter(system.drawing.imaging.encoder.quality, 100l);
bmp.save(filename, getencoder(imageformat.jpeg), encoderparameters);
}

public static void savejpg100(this bitmap bmp, stream stream)
{
var encoderparameters = new encoderparameters(1);
encoderparameters.param[0] = new encoderparameter(system.drawing.imaging.encoder.quality, 100l);
bmp.save(stream, getencoder(imageformat.jpeg), encoderparameters);
}

public static imagecodecinfo getencoder(imageformat format)
{
var codecs = imagecodecinfo.getimagedecoders();

foreach (var codec in codecs)
{
if (codec.formatid == format.guid)
{
return codec;
}
}

// return
return null;
}
}


调用方式如下:

复制代码 代码如下:

websitetoimage websitetoimage = new websitetoimage( "//www.jb51.net", @"d:\some folder\keleyi.jpg");
websitetoimage.generate();

这种方式使用了webbrowser控件,所以必须引用 system.windows.forms 命名空间。