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 @   simadi  阅读(396)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
点击右上角即可分享
微信分享提示