近日有图片通过C#加水印的需求,在网上搜到了这个:https://www.jb51.net/program/319824nmi.htm
但是提供的代码有不少问题。经过分析和修改,整理为了这样的代码:
oldpath为原图片路径,newpath为保存到的图片路径。text为水印文字内容。rotate是以°为单位的角度,repeatD是垂直或水平相邻两次水印的间隔像素(设置为0时只显示一次文字),Trans是水印的透明度。
因为用不到90度的文字,所以只对Math.tan(π/2)报了异常。
源代码中的textWidth 、textHeight几乎是干扰项,实际上制作水印是根据MeasureString(text, font)来计算水印文字的长宽的,xcount和ycount也应该根据此长宽调整数量,而不是固定的+3。
此代码已经在项目中实际使用。
` public void AddWaterText(string oldpath, string text, string newpath, System.Drawing.Font font, Color color, float rotate = 15.0f, int repeatD = 50,int Trans=128)
{
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);
Image imgPhoto = Image.FromStream(ms);
int imgPhotoWidth = imgPhoto.Width;
int imgPhotoHeight = imgPhoto.Height;
Bitmap bmPhoto = new Bitmap(imgPhotoWidth, imgPhotoHeight, PixelFormat.Format24bppRgb);
bmPhoto.SetResolution(72, 72);
Graphics gbmPhoto = Graphics.FromImage(bmPhoto);
gbmPhoto.Clear(Color.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);
SizeF crSize = gbmPhoto.MeasureString(text, font);
float y = 0;
float x = 0;
StringFormat StrFormat = new StringFormat();
StrFormat.Alignment = StringAlignment.Center;
SolidBrush semiTransBrush = new SolidBrush(Color.FromArgb(Trans, color.R, color.G, color.B));
gbmPhoto.RotateTransform(rotate);
if (repeatD == 0)
{
gbmPhoto.DrawString(text, font, semiTransBrush, x, y);
}
else
{
double arc = rotate / 180 * Math.PI;//弧度
if(double.IsInfinity(Math.Tan(arc))) throw new Exception("不允许90度设置水印");
y =(int)(Math.Tan(arc) * imgPhotoWidth);//从这里开始,水印才能覆盖到图像的右上角
int ycount = (int)(imgPhotoHeight / crSize.Height);
ycount += (int)(2 * y / crSize.Height);//使得正向和反向都能用上
y = -y;
x = (int)(imgPhotoHeight / Math.Tan(arc));
int xcount = (int)(imgPhotoWidth / crSize.Width) + 3;
xcount += (int)(2 * x / crSize.Width);
x = -x;
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 += crSize.Width + repeatD;
}
x = ox;
y += crSize.Height + repeatD;
}
}
bmPhoto.Save(newpath);//怎么原代码全存jpg了
gbmPhoto.Dispose();
imgPhoto.Dispose();
bmPhoto.Dispose();
}
`
希望越来越多的开发者在面向百度编程,借用各种博客代码后,能想起来分享一些自己的代码~
标签:imgPhotoHeight,crSize,C#,水印,int,添加,new,gbmPhoto From: https://www.cnblogs.com/hoshitani/p/18224416