图片加水印c#

方法1:

public class WaterTextBox : TextBox
    {
        //private const int EM_SETCUEBANNER = 0x1501;
        //[DllImport("user32.dll", CharSet = CharSet.Auto)]
        //private static extern Int32 SendMessage
        // (IntPtr hWnd, int msg, int wParam, [MarshalAs(UnmanagedType.LPWStr)] string lParam);
        string waterText = string.Empty;
        [Category("外观")]
        [Description("设置水印文本")]
        [DefaultValue(typeof(String), "提示文字")]
        public string WaterText
        {
            get { return waterText; }
            set
            {
                waterText = value;
                this.Invalidate();
            }
        }
        public WaterTextBox()
        {
            //        base.SetStyle(
            //ControlStyles.UserPaint |                      // 控件将自行绘制,而不是通过操作系统来绘制  
            //ControlStyles.OptimizedDoubleBuffer |          // 该控件首先在缓冲区中绘制,而不是直接绘制到屏幕上,这样可以减少闪烁  
            //ControlStyles.AllPaintingInWmPaint |           // 控件将忽略 WM_ERASEBKGND 窗口消息以减少闪烁  
            //ControlStyles.ResizeRedraw |                   // 在调整控件大小时重绘控件  
            //ControlStyles.SupportsTransparentBackColor,    // 控件接受 alpha 组件小于 255 的 BackColor 以模拟透明  
            //true);                                         // 设置以上值为 true  
            //        base.UpdateStyles();
            base.SetStyle(ControlStyles.SupportsTransparentBackColor, true);
            this.BorderStyle = BorderStyle.FixedSingle;
            //this.BorderStyle = Forms.BorderStyle.None;
            this.SuspendLayout();
            this.Font = new System.Drawing.Font("微软雅黑", 9f);
            this.ResumeLayout(false);
            this.WaterText = "水印文字";
            this.AutoSize = false;
            this.Height = 18;
            HelpText = "选择";
            HelpWidth = 40;

        }
        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
        static extern IntPtr LoadLibrary(string lpFileName);

        /// <summary>
        /// 支持透明背景
        /// </summary>
        protected override CreateParams CreateParams
        {
            get
            {
                if (BackColor != Color.Transparent) return base.CreateParams;
                CreateParams prams = base.CreateParams;
                if (LoadLibrary("msftedit.dll") != IntPtr.Zero)
                {
                    prams.ExStyle |= 0x020;
                    prams.ClassName = "RICHEDIT50W";
                }
                return prams;
            }
        }

        public int HelpWidth { get; set; }
        protected override void WndProc(ref Message m)
        {
            base.WndProc(ref m);
            DrawBorder(ref m);
            if (m.Msg == 0xF)
            {
                WmPaint(ref m);
            }


        }
        Point mPoint = Point.Empty;
        protected override void OnMouseMove(MouseEventArgs e)
        {
            mPoint = e.Location;
            base.OnMouseMove(e);
        }

        // public override Cursor Cursor
        //{
        //    get
        //    {
        //        var rect = ClientRectangle;
        //        rect.X = ClientRectangle.Width - HelpWidth;
        //        rect.Width = HelpWidth;
        //        if (rect.Contains(mPoint))
        //            return Cursors.Hand;
        //        return base.Cursor;

        //    }
        //    set
        //    {
        //        base.Cursor = value;
        //    }
        //}
        public Color BorderColor
        {
            get { return borderColor; }
            set { borderColor = value; }
        }
        private Color borderColor = Color.Orange;   // default border color is black
        private static int WM_NCPAINT = 0x0085;    // WM_NCPAINT message
        private static int WM_ERASEBKGND = 0x0014; // WM_ERASEBKGND message
        private static int WM_PAINT = 0x000F;      // WM_PAINT message
        public event Action<Point> OnDrawText;
        public bool IsSelect { get; set; }
        public string HelpText { get; set; }
        StringFormat sf = new StringFormat() { LineAlignment = StringAlignment.Center, Alignment = StringAlignment.Center };
        [DllImport("user32.dll")]
        static extern int SetWindowRgn(IntPtr hWnd, IntPtr hRgn, bool bRedraw);

        [DllImport("gdi32.dll")]
        static extern IntPtr CreateRoundRectRgn(int x1, int y1, int x2, int y2, int cx, int cy);
        public void DrawBorder(ref Message message)
        {
            if (message.Msg == WM_NCPAINT || message.Msg == WM_ERASEBKGND ||
                message.Msg == WM_PAINT)
            {

                using (Graphics graphics = Graphics.FromHwnd(this.Handle))
                {
                    if (this.BorderStyle == BorderStyle.FixedSingle)
                    {
                        Rectangle rectangle = this.ClientRectangle;
                        ControlPaint.DrawBorder(graphics, rectangle,
                                     borderColor, ButtonBorderStyle.Solid);
                        graphics.Dispose();
                        message.Result = (IntPtr)1;
                    }

                    //SetWindowRgn(this.Handle, CreateRoundRectRgn(0, 0, this.Width + 1, Height + 1, 5, 5), true);

                }


            }
        }
        protected override void OnPaintBackground(PaintEventArgs e)
        {

            base.OnPaintBackground(e);
            e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
            using (GraphicsPath path = new GraphicsPath())
            {
                path.AddArc(0, 0, Height - 1, Height - 1, 90, 180);
                path.AddArc(Width - Height, 0, Height - 1, Height - 1, 270, 180);
                path.CloseFigure();

                e.Graphics.FillPath(Brushes.Orange, path);
                using (Pen pen = new Pen(Color.Green))
                {
                    e.Graphics.DrawPath(pen, path);
                }
            }
        }

        private void WmPaint(ref Message m)
        {
            using (Graphics graphics = Graphics.FromHwnd(base.Handle))
            {
                if (string.IsNullOrEmpty(Text))
                {
                    TextFormatFlags format =
                        TextFormatFlags.EndEllipsis |
                         TextFormatFlags.VerticalCenter;
                    if (Multiline)
                    {
                        format =
                 TextFormatFlags.EndEllipsis |
                         TextFormatFlags.VerticalCenter |

                  TextFormatFlags.Left;
                    }
                    if (RightToLeft == RightToLeft.Yes)
                    {
                        format |= TextFormatFlags.RightToLeft | TextFormatFlags.Right;
                    }
                    TextRenderer.DrawText(
                        graphics,
                        WaterText,
                        Font,
                        ClientRectangle,
                        Color.Gray,
                        format);
                }
                //if (IsSelect)
                //{
                //    var rect = ClientRectangle;
                //    rect.X = ClientRectangle.Width - HelpWidth;
                //    rect.Width = HelpWidth;
                //    graphics.FillRectangle(Brushes.Goldenrod, rect);
                //    using (var brush = new SolidBrush(Color.White))
                //        graphics.DrawString(HelpText, Font, brush, rect, sf);
                //     if(OnDrawText!=null)
                //     {
                //         OnDrawText(rect.Location);
                //     }
                //}

            }

        }

    }

方法2:

protected void Button1_Click(object sender, EventArgs e)
    {
        int location = Convert.ToInt32(this.DropDownList1.SelectedValue);//获取水印放置位置


        //判断FileUpload里是否有文件地址
        if (FileUpload1.HasFile)
        {
            if ((FileUpload1.PostedFile.ContentType == "image/pjpeg") || (FileUpload1.PostedFile.ContentType == "image/jpeg") || (FileUpload1.PostedFile.ContentType == "image/gif") || (FileUpload1.PostedFile.ContentType == "image/bmp") || (FileUpload1.PostedFile.ContentType == "image/x-png") || (FileUpload1.PostedFile.ContentType == "image/png"))//获取客户端发送的文件的MIME内容类型
            {
                //上传文件总大小
                int fileLength = 0;
                fileLength = fileLength + FileUpload1.PostedFile.ContentLength;
                //大小不能超过maxLengthk
                int maxLength = 2048;
                int sysLength = maxLength * 1024;
                if (fileLength > sysLength)
                {
                   Response.Write("<script>alert(''''该图片大小超过2M限制'''')</script>");
                }
                else
                {
                    string[] strSpil = FileUpload1.FileName.Split(''''.'''');//将此地址用.号进行分割(img/1.jpg)
                    string strEnd = strSpil[strSpil.Length - 1].ToLower();//得到后面的("jpg", "gif", "bmp", "png","jpeg","JPG","GIF","BMP","PNG","JPEG")
                    string[] strPic = new string[] { "jpg", "gif", "bmp", "png", "jpeg", "JPG", "GIF", "BMP", "PNG", "JPEG" };//定义一个数组里面放文件格式 
                    List<string> arry = new List<string>();
                    arry.AddRange(strPic);  //定义一个可变数组,用于放文件格式
                    if (arry.Contains(strEnd))//判断这个数组中是否有("jpg", "gif", "bmp", "png","jpeg","JPG","GIF","BMP","PNG","JPEG") 
                    {
                        Random rand = new Random();//定义一个随机数,为了防止你要上传得图片重名 
                        string strName = DateTime.Now.ToString("yyyymmmddhhss") + rand.Next(100, 9999).ToString();//得到不同得名字
                        string strPointEnd = "." + strEnd;
                        string strFile = Server.MapPath("~/upfile");//获取其相对地址
                        FileUpload1.SaveAs(strFile + "/" + strName + strPointEnd);//保存原始图片
                        string src = strFile + "/" + strName + strPointEnd;


                        //进行水印添加处理--------------------------------------------
                        //水印图片
                        string shuiyin = "~/watermark/logo.png";
                        //加载文件
                        System.Drawing.Image Cover;
                        Cover = System.Drawing.Image.FromFile(src);
                        //加载水印文件
                        System.Drawing.Image water = System.Drawing.Image.FromFile(Request.MapPath(shuiyin));
                        //创建画布
                        System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(Cover);
                        if (location == 1)//左上方
                        {
                            //在image上绘制水印
                            g.DrawImage(water, new Rectangle(0, 0, water.Width, water.Height), 0, 0, water.Width, water.Height, GraphicsUnit.Pixel);
                        }
                        else if (location == 2)//左下方
                        {
                            //在image上绘制水印
                            g.DrawImage(water, new Rectangle(0, Cover.Height - water.Height, water.Width, water.Height), 0, 0, water.Width, water.Height, GraphicsUnit.Pixel);
                        }
                        else if (location == 3)//右上方
                        {
                            //在image上绘制水印
                            g.DrawImage(water, new Rectangle(Cover.Width - water.Width, 0, water.Width, water.Height), 0, 0, water.Width, water.Height, GraphicsUnit.Pixel);
                        }
                        else if (location == 4)//右下方
                        {
                            //在image上绘制水印
                            g.DrawImage(water, new Rectangle(Cover.Width - water.Width, Cover.Height - water.Height, water.Width, water.Height), 0, 0, water.Width, water.Height, GraphicsUnit.Pixel);
                        }
                        else if (location == 5)//正中间
                        {
                            //在image上绘制水印
                            g.DrawImage(water, new Rectangle((Cover.Width - water.Width) / 2, (Cover.Height - water.Height) / 2, water.Width, water.Height), 0, 0, water.Width, water.Height, GraphicsUnit.Pixel);
                        }
                        else
                        {
                            //在image上绘制水印
                            g.DrawImage(water, new Rectangle(Cover.Width - water.Width, Cover.Height - water.Height, water.Width, water.Height), 0, 0, water.Width, water.Height, GraphicsUnit.Pixel);
                        }
                        //释放画布
                        g.Dispose();
                        //释放水印图片
                        water.Dispose();
                        Cover.Save(HttpContext.Current.Server.MapPath("~/upfile/") + strName+"s"+ "." + strEnd);//保存打过水印的图片
                        Cover.Dispose();
                        string src1 = "upfile/" + strName + "s" + "." + strEnd;
                        Response.Write("<a href="+src1+">点击查看水印图片</a>");
                    }
                    else
                    {
                        Response.Write("<script>alert(''''该图片格式不能上传!'''')</script>");
                    }
                }
            }
            else
            {
               Response.Write("<script>alert(''''该图片格式不能上传!'''')</script>");
            }
        }
        else
        {
            Response.Write("<script>alert(''''请选择图片路径!'''')</script>");
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值