169it科技资讯
169it -->


当前位置:  编程技术>.net/c#/asp.net

Winform实现将网页生成图片的方法

    来源: 互联网  发布时间:2014-11-04

通常浏览器都有将网页生成图片的功能,本文实例讲述了Winform实现将网页生成图片的方法。分享给大家供大家参考。具体方法如下:

工具截图如下:

生成后的图片如下:

手动填写网站地址,可选择图片类型和保持图片地址,来生成页面的图片,当图片路径未选择时则保存桌面;

具体代码如下:

将html生成图片的类

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Text; 
using System.Windows.Forms; 
using System.Drawing.Imaging; 
using System.Runtime.InteropServices; 
using System.Security;
namespace Print
{
  public class Test
  {
    public static Bitmap GetHtmlImage(Uri UrlString, int Width)
    {
      WebBrowser MyControl = new WebBrowser();
      MyControl.Size = new Size(Width, 10);
      MyControl.Url = UrlString;
      while (MyControl.ReadyState != WebBrowserReadyState.Complete)
      {
        Application.DoEvents();
      }
      MyControl.Height = MyControl.Document.Body.ScrollRectangle.Height + 20;
      MyControl.Url = UrlString;
      WebControlImage.Snapshot snap = new WebControlImage.Snapshot();
      Bitmap MyImage = snap.TakeSnapshot(MyControl.ActiveXInstance, new Rectangle(0, 0, MyControl.Width, MyControl.Height));
      MyControl.Dispose();
      return MyImage;
    }
    /// 
    /// WebBrowser获取图形 
    /// 
    private class WebControlImage
    {
      internal static class NativeMethods
      {
        [StructLayout(LayoutKind.Sequential)]
        public sealed class tagDVTARGETDEVICE
        {
          [MarshalAs(UnmanagedType.U4)]
          public int tdSize;
          [MarshalAs(UnmanagedType.U2)]
          public short tdDriverNameOffset;
          [MarshalAs(UnmanagedType.U2)]
          public short tdDeviceNameOffset;
          [MarshalAs(UnmanagedType.U2)]
          public short tdPortNameOffset;
          [MarshalAs(UnmanagedType.U2)]
          public short tdExtDevmodeOffset;
        }
        [StructLayout(LayoutKind.Sequential)]
        public class COMRECT
        {
          public int left;
          public int top;
          public int right;
          public int bottom;
          public COMRECT()
          {
          }
          public COMRECT(Rectangle r)
          {
            this.left = r.X;
            this.top = r.Y;
            this.right = r.Right;
            this.bottom = r.Bottom;
          }
          public COMRECT(int left, int top, int right, int bottom)
          {
            this.left = left;
            this.top = top;
            this.right = right;
            this.bottom = bottom;
          }
          public static NativeMethods.COMRECT FromXYWH(int x, int y, int width, int height)
          {
            return new NativeMethods.COMRECT(x, y, x + width, y + height);
          }
          public override string ToString()
          {
            return string.Concat(new object[] { "Left = ", this.left, " Top ", this.top, " Right = ", this.right, " Bottom = ", this.bottom });
          }
        }
        [StructLayout(LayoutKind.Sequential)]
        public sealed class tagLOGPALETTE
        {
          [MarshalAs(UnmanagedType.U2)]
          public short palVersion;
          [MarshalAs(UnmanagedType.U2)]
          public short palNumEntries;
        }
      }
      public class Snapshot
      {
        /// 
        /// ?煺? 
        /// 
        /// Com 对象 
        /// 图象大小 
        /// 
        public Bitmap TakeSnapshot(object pUnknown, Rectangle bmpRect)
        {
          if (pUnknown == null)
            return null;
          //必须为com对象 
          if (!Marshal.IsComObject(pUnknown))
            return null;
          //IViewObject 接口 
          UnsafeNativeMethods.IViewObject ViewObject = null;
          IntPtr pViewObject = IntPtr.Zero;
          //内存图 
          Bitmap pPicture = new Bitmap(bmpRect.Width, bmpRect.Height);
          Graphics hDrawDC = Graphics.FromImage(pPicture);
          //获取接口 
          object hret = Marshal.QueryInterface(Marshal.GetIUnknownForObject(pUnknown),
          ref UnsafeNativeMethods.IID_IViewObject, out pViewObject);
          try
          {
            ViewObject = Marshal.GetTypedObjectForIUnknown(pViewObject, typeof(UnsafeNativeMethods.IViewObject)) as UnsafeNativeMethods.IViewObject;
            //调用Draw方法 
            ViewObject.Draw((int)System.Runtime.InteropServices.ComTypes.DVASPECT.DVASPECT_CONTENT,
            -1,
            IntPtr.Zero,
            null,
            IntPtr.Zero,
            hDrawDC.GetHdc(),
            new NativeMethods.COMRECT(bmpRect),
            null,
            IntPtr.Zero,
            0);
          }
          catch (Exception ex)
          {
            Console.WriteLine(ex.Message);
            throw ex;
          }
          //释放 
          hDrawDC.Dispose();
          return pPicture;
        }
      }
      [SuppressUnmanagedCodeSecurity]
      internal static class UnsafeNativeMethods
      {
        public static Guid IID_IViewObject = new Guid("{0000010d-0000-0000-C000-000000000046}");
        [ComImport, Guid("0000010d-0000-0000-C000-000000000046"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
        public interface IViewObject
        {
          [PreserveSig]
          int Draw([In, MarshalAs(UnmanagedType.U4)] int dwDrawAspect, int lindex, IntPtr pvAspect, [In] NativeMethods.tagDVTARGETDEVICE ptd, IntPtr hdcTargetDev, IntPtr hdcDraw, [In] NativeMethods.COMRECT lprcBounds, [In] NativeMethods.COMRECT lprcWBounds, IntPtr pfnContinue, [In] int dwContinue);
          [PreserveSig]
          int GetColorSet([In, MarshalAs(UnmanagedType.U4)] int dwDrawAspect, int lindex, IntPtr pvAspect, [In] NativeMethods.tagDVTARGETDEVICE ptd, IntPtr hicTargetDev, [Out] NativeMethods.tagLOGPALETTE ppColorSet);
          [PreserveSig]
          int Freeze([In, MarshalAs(UnmanagedType.U4)] int dwDrawAspect, int lindex, IntPtr pvAspect, [Out] IntPtr pdwFreeze);
          [PreserveSig]
          int Unfreeze([In, MarshalAs(UnmanagedType.U4)] int dwFreeze);
          void SetAdvise([In, MarshalAs(UnmanagedType.U4)] int aspects, [In, MarshalAs(UnmanagedType.U4)] int advf, [In, MarshalAs(UnmanagedType.Interface)] System.Runtime.InteropServices.ComTypes.IAdviseSink pAdvSink);
          void GetAdvise([In, Out, MarshalAs(UnmanagedType.LPArray)] int[] paspects, [In, Out, MarshalAs(UnmanagedType.LPArray)] int[] advf, [In, Out, MarshalAs(UnmanagedType.LPArray)] System.Runtime.InteropServices.ComTypes.IAdviseSink[] pAdvSink);
        }
      }
    }
  }
}

winfrom后台处理方面代码如下

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Imaging;

namespace Excel文件处理
{
  public partial class Html : Form
  {
    public Html()
    {
      InitializeComponent();
    }
    private string ImageUrl = "";//图片地址
    private string ImageName = "";//图片名称
    private void button1_Click(object sender, EventArgs e)
    {
      string HtmlUrl = this.Txt_Url.Text.Trim(); 
      if (HtmlUrl=="")
      {
        MessageBox.Show("请输入网址");
        return;
      } 
      if (ImageUrl.Trim()=="")
      { 
        ImageUrl = @"C:\Users\Administrator\Desktop";  
      }
      try
      {
        Uri ri = new Uri(this.Txt_Url.Text);
        Bitmap bit = Print.Test.GetHtmlImage(ri, 1200);
        ImageName = this.Txt_Name.Text.Trim();//图片名称
        if (ImageName != "")
        {
          if (ImageName.IndexOf('.') != -1)
          {//当用户输入图片后缀时,将后缀截取
            ImageName.Substring(0, ImageName.LastIndexOf('.'));
          }
        }
        else
          ImageName = DateTime.Now.Ticks.ToString();//时间名称
        switch (this.comboBox1.SelectedText)
        {
          case "GIF": ImageUrl += "\\" + ImageName + ".gif"; break;
          case "JPG": ImageUrl += "\\" + ImageName + ".jpg"; break;
          case "PNG": ImageUrl += "\\" + ImageName + ".png"; break;
          default: ImageUrl += "\\" + ImageName + ".png"; break;
        }

        switch (this.comboBox1.SelectedText)
        {
          case "GIF": bit.Save(ImageUrl, ImageFormat.Gif); break;
          case "JPG": bit.Save(ImageUrl, ImageFormat.Jpeg); break;
          case "PNG": bit.Save(ImageUrl, ImageFormat.Png); break;
          default: bit.Save(ImageUrl, ImageFormat.Png); break;
        }

        bit = null;
        ImageUrl = "";//图片地址
        ImageName = "";//图片名称
        MessageBox.Show("生产成功");
      }
      catch
      {
        MessageBox.Show("网址输入有误!");
        return;
      }
    }

    private void button2_Click(object sender, EventArgs e)
    { 
      //获取保存路径
      if (this.folderBrowserDialog1.ShowDialog()==DialogResult.OK)
      {
        if (this.folderBrowserDialog1.SelectedPath.Trim()!="")
        {
          ImageUrl = folderBrowserDialog1.SelectedPath;
          this.label6.Text = ImageUrl;
        }
      }
    }
  }
}

希望本文所述对大家的C#程序设计有所帮助。


    
相关技术文章:
    ▪C#控制台程序中处理2个关闭事件的代码实例

     应用场景 我们开发的控制台应用,在运行阶段很有可能被用户Ctrl+C终止或是被用户直接关闭。如果我们不希望用户通过Ctrl+C终止我们的程序,就需要对Ctrl+C或关闭事件作处理。 处理方法 在.net平台下Console类有个CancelKeyPress事件可以处理Ctrl+C,不过对于直接关闭控制台应用,这种处理就无能为力了。 不过Windows API中有个SetConsoleCtrlHandler函数可以处理这两种关闭事件。 C#处理代码如下: 代码如下: static class Program {     public delegate bool ControlCtrl......


    ▪WinForm实现同时让两个窗体有激活效果的特效实例

     本文实例讲述了WinForm实现同时让两个窗体有激活效果的特效。主要采用windows api实现一个窗体激活的时候给另外一个发消息。分享给大家供大家参考。 具体实现方法如下: using System; using System.Windows.Forms; using System.Runtime.InteropServices; namespace WindowsApplication43 { public partial class Form1 : Form { Form frm =null; public Form1() { InitializeComponent(); this.Activated += Form_Activated; } const int WM_NCACTIVATE = 0x86; const int WA_ACTIVE = 0x1; [DllImport("user32.dll", EntryPoint = "SendMessage")] public static extern int S......


    ▪WinForm实现拦截窗体上各个部位的点击特效实例

     本文实例讲述了WinForm实现拦截窗体上各个部位的点击特效,是一个非常实用的技巧。分享给大家供大家参考。具体分析如下: 一般来说,windows窗体的标题栏无法直接通过一些默认的事件来控制,需要了解和WM_NCHITTEST相关的windows消息。 以下示例演示了最简单的效果片断:他会把客户区和标题栏的效果互换,比如无法按住标题栏拖动窗体而是改为了按住客户区拖动,并禁用了关闭按钮。 其中m.Result从-2到21都有定义,分别对应了整个窗体的各个部位,比如1代表客户区,8代表最小化按钮等等。 具体功能代码如下: ......


 
最新技术文章:
    ▪C#通过IComparable实现ListT.sort()排序

     本文实例讲述了C#通过IComparable实现ListT.sort()排序的方法,分享给大家供大家参考之用。具体方法如下: 通常来说,List<T>.sort()可以实现对T的排序,比如List<int>.sort()执行后集合会按照int从小到大排序。如果T是一个自定义的Object,可是我们想按照自己的方式来排序,那该怎么办呢,其实可以用过IComparable接口重写CompareTo方法来实现。流程如下: 一、第一步我们申明一个类Person但是要继承IComparable接口: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TestIC......


    ▪C#实现对Json字符串处理实例

     本文实例讲述了C#实现对Json字符串处理方法,分享给大家供大家参考。具体分析如下: 一般对于web应用开发人员来说对Json字符串都会很熟悉,其实在很多请求我们返回的都是Json字符串。那对于C#代码如何处理Json字符串呢,.Net封装了一个类叫做JavaScriptSerializer[MSDN Library 链接:http://msdn.microsoft.com/en-us/library/ee191864(v=vs.110).aspx];这个类提供了一个方法。 下面这个是在快递100往抓取的一个圆通的快递信息。对于我们有用的信息是快递时间,快递状况。那我该如何来做。  ......


    ▪Winform实现抓取web页面内容的方法

     本文以一个非常简单的实例讲述了Winform实现抓取web页面内容的方法,代码简洁易懂,非常实用!分享给大家供大家参考。 具体实现代码如下: WebRequest request = WebRequest.Create("http://1.bjapp.sinaapp.com/play.php?a=" + PageUrl); WebResponse response = request.GetResponse(); Stream resStream = response.GetResponseStream(); StreamReader sr = new StreamReader(resStream, System.Text.Encoding.UTF8); string htmlinfo = sr.ReadToEnd(); resStream.Close(); sr.Close(); 感兴趣的朋友可以测试运行或改进本文实例。希望本文所述对大家C#程序设计的学习有所帮助。 ......


 


站内导航:


特别声明:169IT网站部分信息来自互联网,如果侵犯您的权利,请及时告知,本站将立即删除!

©2012-2017,169IT.COM,E-mail:www_169it_com#163.com(请将#改为@)

浙ICP备11055608号