c# 实现图片中45度角间隔显示文字水印 可用与电商项目中显示入住商城商户的资料信息外部展示 用于添加水印效果
/// <summary> /// 添加水印 /// </summary> /// <param name="imgPath">原图片地址</param> /// <param name="sImgPath">水印图片地址</param> /// <returns>resMsg[0] 成功,失败 </returns> public static string[] AddWaterMark(string imgPath, string sImgPath) { string[] resMsg = new[] { "成功", sImgPath }; using (Image image = Image.FromFile(imgPath)) { try { Bitmap bitmap = new Bitmap(image); Color markcolor = Color.Red; int degree = 45; //图片的宽度与高度 int width = bitmap.Width, height = bitmap.Height; //水印文字 string text = "****入驻专用 其他无效"; Graphics g = Graphics.FromImage(bitmap); int rowsNumber, columnsNumber; //图片宽度与高度 用于横向与竖向水印文字 if (width > height) { rowsNumber = height /20; columnsNumber = width / 200; }else { rowsNumber = height /200; columnsNumber = width / 20; } if (rowsNumber < 1) { rowsNumber = 1; } if (columnsNumber < 1) { columnsNumber = 1; } 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("微软雅黑", 12, FontStyle.Bold); SizeF crSize = new SizeF(); crSize = g.MeasureString(text, crFont); SolidBrush semiTransBrush = new SolidBrush(Color.FromArgb(120, 137, 131, 131)); //将原点移动 到图片中点 g.TranslateTransform(0 , height ); //以原点为中心 转 -45度 g.RotateTransform(-45); for (int j = 0; j < rowsNumber; j++) { for (int i = 0; i < columnsNumber; i++) { g.DrawString(text, crFont, semiTransBrush, new PointF(i * 100 + j * 200, -i * 100 + j * 200)); } } //保存文件 bitmap.Save(sImgPath, System.Drawing.Imaging.ImageFormat.Jpeg); } catch (Exception e) { resMsg[0] = "失败"; resMsg[1] = e.Message; } } return resMsg; }