C#页面生成图片

1、页面生成图片工具

2、生成图片结果


3、源码分享

/// <summary>
        /// 生成图片
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnBuild_Click(object sender, EventArgs e)
        {
            string HtmlUrl = this.txtUrl.Text.Trim();
            if (HtmlUrl == "")
            {
                MessageBox.Show("请输入网址");
                return;
            }
            if (ImageUrl.Trim() == "")
            {
                ImageUrl = @"C:\Users\Administrator\Desktop";
            }

            try
            {
                Uri ri = new Uri(this.txtUrl.Text);
                Bitmap bit = TurnImage.GetHtmlImage(ri, 1200);
                ImageName = this.txtImgName.Text.Trim();//图片名称
                if (ImageName != "")
                {
                    if (ImageName.IndexOf('.') != -1)
                    {
                        //当用户输入图片后缀时,将后缀截取
                        ImageName.Substring(0, ImageName.LastIndexOf('.'));
                    }
                }
                else
                    ImageName = DateTime.Now.Ticks.ToString();//时间名称
                switch (this.cboImgType.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.cboImgType.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;
            }
        }

        /// <summary>
        /// 另存为
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSave_Click(object sender, EventArgs e)
        {
            //获取保存路径
            if (this.folderBrowserDialog1.ShowDialog() == DialogResult.OK)
            {
                if (this.folderBrowserDialog1.SelectedPath.Trim() != "")
                {
                    ImageUrl = folderBrowserDialog1.SelectedPath;
                    this.label6.Text = ImageUrl;
                }
            }
        }

public class TurnImage
    {
        public static Bitmap GetHtmlImage(Uri UrlString, int Width)
        {
            WebBrowser wb = new WebBrowser();
            wb.Size = new Size(Width, 10);
            wb.Url = UrlString;
            while (wb.ReadyState != WebBrowserReadyState.Complete)
            {
                Application.DoEvents();
            }
            wb.Height = wb.Document.Body.ScrollRectangle.Height + 20;
            wb.Url = UrlString;
            WebControlImage.Snapshot snap = new WebControlImage.Snapshot();
            Bitmap bitImg = snap.TakeSnapshot(wb.ActiveXInstance, new Rectangle(0, 0, wb.Width, wb.Height));
            wb.Dispose();
            return bitImg;
        }

        /// 
        /// 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
            {
                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);
                }
            }
        }
    }

有感兴趣的朋友可以下载,下载地址:http://bbs.netluntan.com/showtopic-422.aspx

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值