string filename) { var encoderParameters = new EncoderParam

时间:2021-12-17 04:48:49

引用 System.Windows.Forms 定名空间:

WebsiteToImage websiteToImage = new WebsiteToImage("页面路径", @"图片生存路径");
websiteToImage.Generate();

被挪用代码:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Drawing;

using System.Threading;

using System.Windows.Forms;

using System.Drawing.Imaging;

using System.IO;

namespace Business {

public class WebsiteToImage {

private Bitmap m_Bitmap;

private string m_Url;

private string m_FileName = string.Empty;

public WebsiteToImage(string url)

{

m_Url = url;

}

/// </summary>
/// <param>网页路径</param>
/// <param>照片存储路径</param>

public WebsiteToImage(string url, string fileName)

{

m_Url = url;

m_FileName = fileName;

public Bitmap Generate()

{

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)

{

var browser = (WebBrowser)sender;

//宽,,高

browser.ClientSize = new Size(618,500);

browser.ScrollBarsEnabled = false;

//宽,高

m_Bitmap = new Bitmap(618, 500);

browser.BringToFront();

browser.DrawToBitmap(m_Bitmap, browser.Bounds);

if (m_FileName.Length > 0)

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)

{