C# 给图片添加文字水印

目录

应用场景

开发运行环境

方法说明

方法代码

调用示例 

小结


应用场景

在某些应用项目(如电子档案信息管理)中,查看电子图片信息是经常使用到的功能,此时我们就需要给显示在浏览器中的图片添加文字水印版权或提示信息。增加水印主要起到如下作用:

1、防止盗图:图片加水印可以有效防止盗图,将文字水印嵌入到图片中作为特殊标记,可以在不影响图片质量的情况下保护版权,即使别人下载了图片,也可以通过水印追踪到图片的来源。

2、增加宣传效果:可以通过添加URL或其它宣传性文字,增加宣传效果。

开发运行环境

操作系统: Windows Server 2019 DataCenter

.net版本: .netFramework4.0 或以上

开发工具:VS2019  C#

方法说明

AddWaterText 方法无返回值,具体参数说明请参照下表:

序号参数名类型说明
1oldpathstring原图片文件路径
2textstring要添加的水印文字
3newpathstring新输出图片文件路径
4pointobject设置文字起始位置坐标
5fontSystem.Drawing.Font设置文字的字体
6colorSystem.Drawing.Color

设置文字的颜色

可使用 System.Drawing.Color.FromArgb(alpha, r, g, b)方法添加滤镜效果

7rotatefloat旋转角度值,默认值为 0.0f
8textWidthint文本预估宽度,默认值为1
9textHeightint文本预估高度,默认值为1
10repeatDint多水印文本间距值,默认值为0

方法代码

public void AddWaterText(string oldpath, string text, string newpath, object point, System.Drawing.Font font, System.Drawing.Color color, float rotate = 0.0f, int textWidth = 1,int textHeight=1, int repeatD=0)
		{
			
			try
			{
				FileStream fs = new FileStream(oldpath, FileMode.Open);
				BinaryReader br = new BinaryReader(fs);
				byte[] bytes = br.ReadBytes((int)fs.Length);
				br.Close();
				fs.Close();
				MemoryStream ms = new MemoryStream(bytes);

				System.Drawing.Image imgPhoto = System.Drawing.Image.FromStream(ms);
				int imgPhotoWidth = imgPhoto.Width;
				int imgPhotoHeight = imgPhoto.Height;

				Bitmap bmPhoto = new Bitmap(imgPhotoWidth, imgPhotoHeight, System.Drawing.Imaging.PixelFormat.Format24bppRgb);

				bmPhoto.SetResolution(72, 72);
				Graphics gbmPhoto = Graphics.FromImage(bmPhoto);
				gbmPhoto.Clear(Color.FromName("white"));
				gbmPhoto.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
				gbmPhoto.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
				gbmPhoto.DrawImage(imgPhoto, new Rectangle(0, 0, imgPhotoWidth, imgPhotoHeight), 0, 0, imgPhotoWidth, imgPhotoHeight, GraphicsUnit.Pixel);
				System.Drawing.SizeF crSize = new SizeF();
				crSize = gbmPhoto.MeasureString(text, font);
				float y = imgPhotoHeight - crSize.Height;
				float x = imgPhotoWidth - crSize.Width;

				System.Drawing.StringFormat StrFormat = new System.Drawing.StringFormat();
				StrFormat.Alignment = System.Drawing.StringAlignment.Center;

				if(point!=null)
				{
					System.Drawing.Point newpos=((System.Drawing.Point)point);
					x=newpos.X;
					y=newpos.Y;
				}


				System.Drawing.SolidBrush semiTransBrush = new System.Drawing.SolidBrush(color);
				System.Drawing.Color.FromArgb(1,1,1,1);
                gbmPhoto.RotateTransform(rotate);
                if (repeatD == 0)
                {
                    gbmPhoto.DrawString(text, font, semiTransBrush, x, y);
                }
                else
                {
                    int xcount = imgPhotoWidth/textWidth+3;
                    int ycount = imgPhotoHeight/textHeight+3;
                    float ox = x;
                    for (int k = 0; k < ycount; k++)
                    {
                        for (int i = 0; i < xcount; i++)
                        {
                            for (int j = 0; j < xcount; j++)
                            {

                                gbmPhoto.DrawString(text, font, semiTransBrush, x, y);
                            }
                            x += textWidth+repeatD;
                        }
                        x = ox;
                        y += textHeight+repeatD;
                    }
                }
				bmPhoto.Save(newpath, System.Drawing.Imaging.ImageFormat.Jpeg);
				gbmPhoto.Dispose();
				imgPhoto.Dispose();
				bmPhoto.Dispose();
			}
			catch
			{               
				;               
			}
		}

调用示例 

//获取源图片文件路径
string tempfile=Request.PhysicalApplicationPath+"\\app_data\\test.jpg";
//设置文字位置
System.Drawing.Point point = new System.Drawing.Point();
point.X = -10;
point.Y = -100;
//设置字体类
System.Drawing.Font font = new System.Drawing.Font("微软雅黑", 19, System.Drawing.FontStyle.Bold);
//设置字体滤镜值 ,和RGB分量颜色
int alpha = 25; int r = 255; int g = 0; int b = 255;
System.Drawing.Color color = System.Drawing.Color.FromArgb(alpha, r, g, b);

 
float rotate=30.0f; // 旋转角度
int textWidth = 100; //文本预估宽度
int textHeight=30; //文本预估高度
int repeatD=100; // 多水印文本间距,则表示多水印输出

//添加水印文字
string text="版权所有";
AddWaterText(tempfile,text,tempfile, point, font, color,rotate,textWidth,textHeight,repeatD);

File.Delete(tempfile);  //删除释放文件,在些之前可执行显示操作,如获取base64编码

显示效果如下图:

小结

AddWaterText 方法需要根据您实际应用中的图片大小动态调整参数,以达到满意的显示效果,如果文字起始位置,字体大小,水印间距等。您也可以改造本方法或应用,自动适应调整参数值。

调用示例中新旧图片文件输出为同一文件,然后删除释放文件所占用磁盘的空间,因此我们想要正确显示图片在浏览器的话,需要在删除文件前获取图片的Base64编码即可,如何获取base64数据的方法请参照我的文章:《C# 自动填充文字内容到指定图片》

感谢您的阅读,希望本文能够对您有所帮助。

  • 43
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 15
    评论
可以使用C#中的GDI+库来给图片添加水印效果。以下是一个简单的示例代码: ```csharp using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; public static Image AddWatermark(Image image, string watermarkText, Font font, Color color, float opacity, PointF position) { // 创建一个与原图相同大小的Bitmap对象 Bitmap bitmap = new Bitmap(image.Width, image.Height, PixelFormat.Format32bppArgb); // 创建一个Graphics对象,用于绘制水印 using (Graphics graphics = Graphics.FromImage(bitmap)) { // 将Graphics对象的渲染质量设置为高质量 graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; graphics.SmoothingMode = SmoothingMode.HighQuality; graphics.CompositingQuality = CompositingQuality.HighQuality; // 绘制原图 graphics.DrawImage(image, new Rectangle(0, 0, bitmap.Width, bitmap.Height), 0, 0, image.Width, image.Height, GraphicsUnit.Pixel); // 创建一个Brush对象,用于绘制水印文字 Brush brush = new SolidBrush(Color.FromArgb((int)(opacity * 255), color)); // 绘制水印文字 graphics.DrawString(watermarkText, font, brush, position); // 释放Brush对象 brush.Dispose(); } // 返回添加水印后的图片 return bitmap; } ``` 以上代码中,`AddWatermark`方法接受以下参数: - `image`:要添加水印图片。 - `watermarkText`:要添加水印文字。 - `font`:水印文字的字体。 - `color`:水印文字的颜色。 - `opacity`:水印文字的不透明度,取值范围为0-1。 - `position`:水印文字的位置。 使用示例: ```csharp Image image = Image.FromFile("sample.jpg"); Font font = new Font("Arial", 24); Color color = Color.White; float opacity = 0.5f; PointF position = new PointF(10, 10); Image newImage = AddWatermark(image, "Sample Watermark", font, color, opacity, position); newImage.Save("sample-with-watermark.jpg", ImageFormat.Jpeg); ``` 以上示例中,我们从文件中加载了一张名为`sample.jpg`的图片,然后使用`AddWatermark`方法添加了一个水印,最后将添加水印后的图片保存为`sample-with-watermark.jpg`。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

初九之潜龙勿用

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

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

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

打赏作者

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

抵扣说明:

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

余额充值