C# 图片添加水印

调用

WaterMarkHelper.AddWaterMark(@"C:\Users\xxxue\Desktop\QQ图片20180704142029.jpg", @"C:\Users\xxxue\Desktop\123.jpg",);

核心代码

        /// <summary>
        /// 添加水印
        /// </summary>
        /// <param name="imgPath">原图片地址</param>
        /// <param name="sImgPath">加水印厚图片地址</param>
        /// <param name="text">文字</param>
        /// <param name="size">大小-30</param>
        /// <param name="location">012左中右</param>
        /// <param name="c">颜色</param>
        /// <returns>成功,失败 </returns>
        public static bool AddWaterMarkText(string imgPath, string sImgPath, string text,int size,int location,Color c)
        {
            using (Image image = Image.FromFile(imgPath))
            {
                try
                {
                    Bitmap bitmap = new Bitmap(image);
                    int width = bitmap.Width, height = bitmap.Height;
                    Graphics g = Graphics.FromImage(bitmap);
                    g.DrawImage(bitmap, 0, 0);
                    g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
                    g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                    g.DrawImage(image, new Rectangle(0, 0, width, height), 0, 0, width, height, GraphicsUnit.Pixel);

                    Font crFont = new Font("微软雅黑", size, FontStyle.Bold);
                    SizeF crSize = new SizeF();
                    crSize = g.MeasureString(text, crFont);//文字大小
                    //背景位置(去掉了. 如果想用可以自己调一调 位置.)
                    //graphics.FillRectangle(new SolidBrush(Color.FromArgb(200, 255, 255, 255)), (width - crSize.Width) / 2, (height - crSize.Height) / 2, crSize.Width, crSize.Height);
                    SolidBrush semiTransBrush = new SolidBrush(Color.FromArgb(120, c.R, c.G, c.B));
                    //将原点移动 到图片中点
                    if (location==0)
                    {
                        g.TranslateTransform(10, 10);
                    }
                    else if (location==1)
                    {
                        g.TranslateTransform((width- crSize.Width) / 2, 10);
                    }
                    else
                    {
                        g.TranslateTransform(width- crSize.Width -10, 10);
                    }
                    g.DrawString(text, crFont, semiTransBrush, new PointF(0, 0));
                    //保存文件
                    bitmap.Save(sImgPath, ImageFormat.Jpeg);
                    return true;
                }
                catch (Exception e)
                {
                    return false;
                }
            }
        }

 

posted @ 2021-09-30 10:00  simadi  阅读(392)  评论(0编辑  收藏  举报