C# 实现上传全图加水印

本文介绍了一个C#项目中实现全图水印的需求,包括处理带有索引像素格式的图像创建Graphics对象时遇到的问题。通过检查图片的PixelFormat,确保不是索引像素格式,然后应用旋转和透明度来实现斜角水印。代码示例展示了如何使用Graphics对象和SolidBrush在图片上绘制多个水印文本,以达到全图覆盖的效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近一个项目中要求收集客户的图片要全部加上水印,主要是满足系统收集信息符合相关安全规定,百度找到一堆都是在图片的某个位置增加一条水印的,没有满足客户经理要求全图增加水印的要求,客户经理要的效果如下:

同时在实现该功能后,还遇到 “无法从带有索引像素格式的图像创建graphics对象”这个错误

综合以上问题,处理出如下代码:

满足针对图片文件,弥补 “无法从带有索引像素格式的图像创建graphics对象”的错误,实现全图水印功能:

统一封装如ImageUtil静态类

1、判断上传的文件是否为图片:

public static Boolean IsImage(HttpPostedFileBase file)
        {
            try
            {
                System.Drawing.Image img = System.Drawing.Image.FromStream(file.InputStream, true, true);
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

2、出现无法从带有索引像素格式的图像创建graphics对象,原因是因为图片是索引像素格式的,所以要增加判断

#region 无法从带有索引像素格式的图像创建graphics对象,判断是否位索引像素图片

        private static PixelFormat[] indexedPixelFormats = { PixelFormat.Undefined, PixelFormat.DontCare,
                PixelFormat.Format16bppArgb1555, PixelFormat.Format1bppIndexed, PixelFormat.Format4bppIndexed,
                PixelFormat.Format8bppIndexed};

        /// <summary>
        /// 判断图片的PixelFormat 是否在 引发异常的 PixelFormat 之中
        /// </summary>
        /// <param name="imgPixelFormat">原图片的PixelFormat</param>
        /// <returns></returns>
        private static bool IsPixelFormatIndexed(PixelFormat imgPixelFormat)
        {
            foreach (PixelFormat pf in indexedPixelFormats)
            {
                if (pf.Equals(imgPixelFormat)) return true;
            }

            return false;
        }

        #endregion

3、实现增加水印方法(全图斜角微透明水印)

/// <summary>
        /// 文字水印
        /// </summary>
        /// <param name="imgPath">图片绝对路径</param>
        /// <param name="watermarkText">水印文字</param>
        /// <param name="watermarkStatus">图片水印位置 0=不使用 1=左上 2=中上 3=右上 4=左中  9=右下</param>
        /// <param name="quality">附加水印图片质量,0-100</param>
        /// <param name="fontsize">字体大小</param>
        /// <param name="fontname">字体</param>
        public static void AddImageSignText(string imgPath, string watermarkText, int watermarkStatus, int quality, int fontsize, string fontname = "微软雅黑")
        {
            byte[] _ImageBytes = File.ReadAllBytes(imgPath);
            Image img = Image.FromStream(new System.IO.MemoryStream(_ImageBytes));
            string filename = imgPath;

            if (IsPixelFormatIndexed(img.PixelFormat))
            {
                Bitmap bmp = new Bitmap(img);
                Graphics g = Graphics.FromImage(bmp);
                g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                g.DrawImage(bmp, 0, 0);

                Font drawFont = new Font(fontname, fontsize, FontStyle.Regular, GraphicsUnit.Pixel);
                SizeF crSize;
                crSize = g.MeasureString(watermarkText, drawFont);

                //float xpos = 0;
                //float ypos = 0;

                //switch (watermarkStatus)
                //{
                //    case 1:
                //        xpos = (float)img.Width * (float).01;
                //        ypos = (float)img.Height * (float).01;
                //        break;
                //    case 2:
                //        xpos = ((float)img.Width * (float).50) - (crSize.Width / 2);
                //        ypos = (float)img.Height * (float).01;
                //        break;
                //    case 3:
                //        xpos = ((float)img.Width * (float).99) - crSize.Width;
                //        ypos = (float)img.Height * (float).01;
                //        break;
                //    case 4:
                //        xpos = (float)img.Width * (float).01;
                //        ypos = ((float)img.Height * (float).50) - (crSize.Height / 2);
                //        break;
                //    case 5:
                //        xpos = ((float)img.Width * (float).50) - (crSize.Width / 2);
                //        ypos = ((float)img.Height * (float).50) - (crSize.Height / 2);
                //        break;
                //    case 6:
                //        xpos = ((float)img.Width * (float).99) - crSize.Width;
                //        ypos = ((float)img.Height * (float).50) - (crSize.Height / 2);
                //        break;
                //    case 7:
                //        xpos = (float)img.Width * (float).01;
                //        ypos = ((float)img.Height * (float).99) - crSize.Height;
                //        break;
                //    case 8:
                //        xpos = ((float)img.Width * (float).50) - (crSize.Width / 2);
                //        ypos = ((float)img.Height * (float).99) - crSize.Height;
                //        break;
                //    case 9:
                //        xpos = ((float)img.Width * (float).99) - crSize.Width;
                //        ypos = ((float)img.Height * (float).99) - crSize.Height;
                //        break;
                //}

                //g.DrawString(watermarkText, drawFont, new SolidBrush(Color.White), xpos + 1, ypos + 1);
                //g.DrawString(watermarkText, drawFont, new SolidBrush(Color.Black), xpos, ypos);

                SolidBrush semiTransBrush = new SolidBrush(Color.FromArgb(60, 137, 131, 131));
                //将原点移动 到图片中点
                g.TranslateTransform(0, crSize.Height);
                //以原点为中心 转 -45度
                g.RotateTransform(-45);
                for (int i = 0; i < 50; i++)
                {
                    g.DrawString(watermarkText, drawFont, semiTransBrush, new PointF(0 - i * 300, 100 + i * 300));
                    g.DrawString(watermarkText, drawFont, semiTransBrush, new PointF(150 - i * 300, 500 + i * 300));
                    g.DrawString(watermarkText, drawFont, semiTransBrush, new PointF(650 - i * 300, 600 + i * 300));
                }

                bmp.Save(filename);
                g.Dispose();
                bmp.Dispose();
                img.Dispose();
            }
            else
            {
                Graphics g = Graphics.FromImage(img);
                Font drawFont = new Font(fontname, fontsize, FontStyle.Regular, GraphicsUnit.Pixel);
                SizeF crSize;
                crSize = g.MeasureString(watermarkText, drawFont);

                //float xpos = 0;
                //float ypos = 0;

                //switch (watermarkStatus)
                //{
                //    case 1:
                //        xpos = (float)img.Width * (float).01;
                //        ypos = (float)img.Height * (float).01;
                //        break;
                //    case 2:
                //        xpos = ((float)img.Width * (float).50) - (crSize.Width / 2);
                //        ypos = (float)img.Height * (float).01;
                //        break;
                //    case 3:
                //        xpos = ((float)img.Width * (float).99) - crSize.Width;
                //        ypos = (float)img.Height * (float).01;
                //        break;
                //    case 4:
                //        xpos = (float)img.Width * (float).01;
                //        ypos = ((float)img.Height * (float).50) - (crSize.Height / 2);
                //        break;
                //    case 5:
                //        xpos = ((float)img.Width * (float).50) - (crSize.Width / 2);
                //        ypos = ((float)img.Height * (float).50) - (crSize.Height / 2);
                //        break;
                //    case 6:
                //        xpos = ((float)img.Width * (float).99) - crSize.Width;
                //        ypos = ((float)img.Height * (float).50) - (crSize.Height / 2);
                //        break;
                //    case 7:
                //        xpos = (float)img.Width * (float).01;
                //        ypos = ((float)img.Height * (float).99) - crSize.Height;
                //        break;
                //    case 8:
                //        xpos = ((float)img.Width * (float).50) - (crSize.Width / 2);
                //        ypos = ((float)img.Height * (float).99) - crSize.Height;
                //        break;
                //    case 9:
                //        xpos = ((float)img.Width * (float).99) - crSize.Width;
                //        ypos = ((float)img.Height * (float).99) - crSize.Height;
                //        break;
                //}

                //g.DrawString(watermarkText, drawFont, new SolidBrush(Color.White), xpos + 1, ypos + 1);
                //g.DrawString(watermarkText, drawFont, new SolidBrush(Color.Black), xpos, ypos);

                SolidBrush semiTransBrush = new SolidBrush(Color.FromArgb(60, 137, 131, 131));
                //将原点移动 到图片中点
                g.TranslateTransform(0, crSize.Height);
                //以原点为中心 转 -45度
                g.RotateTransform(-45);
                for (int i = 0; i < 50; i++)
                {
                    g.DrawString(watermarkText, drawFont, semiTransBrush, new PointF(0 - i * 300, 100 + i * 300));
                    g.DrawString(watermarkText, drawFont, semiTransBrush, new PointF(150 - i * 300, 500 + i * 300));
                    g.DrawString(watermarkText, drawFont, semiTransBrush, new PointF(650 - i * 300, 600 + i * 300));
                }

                ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
                ImageCodecInfo ici = null;
                foreach (ImageCodecInfo codec in codecs)
                {
                    if (codec.MimeType.IndexOf("jpeg") > -1)
                        ici = codec;
                }
                EncoderParameters encoderParams = new EncoderParameters();
                long[] qualityParam = new long[1];
                if (quality < 0 || quality > 100)
                    quality = 80;

                qualityParam[0] = quality;

                EncoderParameter encoderParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qualityParam);
                encoderParams.Param[0] = encoderParam;

                if (ici != null)
                    img.Save(filename, ici, encoderParams);
                else
                    img.Save(filename);

                g.Dispose();
                img.Dispose();
            }
        }

完成;最终效果如下图:

完成此工作,感谢几位博文:

无法从带有索引像素格式的图像创建graphics对象_东亮博客-CSDN博客

c# 图文添加文字斜水印 - Mr_Sun - 博客园

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

石头商人

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值