public class imgTextWater
{
public imgTextWater()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
public bool TextWater(string ImgFile, string TextFont, string sImgPath, int Alpha, float widthFont, float hScale)
{
try
{
FileStream fs = new FileStream(ImgFile, 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"));//gif背景色
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);
//建立字体大小的数组,循环找出适合图片的水印字体
int[] sizes = new int[] { 1000, 800, 700, 650, 600, 560, 540, 500, 450, 400, 380, 360, 340, 320, 300, 280, 260, 240, 220, 200, 180, 160, 140, 120, 100, 80, 72, 64, 48, 32, 28, 26, 24, 20, 28, 16, 14, 12, 10, 8, 6, 4, 2 };
System.Drawing.Font crFont = null;
System.Drawing.SizeF crSize = new SizeF();
for (int i = 0; i < 43; i++)
{
crFont = new Font("黑体", sizes[i], FontStyle.Bold);
crSize = gbmPhoto.MeasureString(TextFont, crFont);
if ((ushort)crSize.Width < (ushort)imgPhotoWidth * widthFont)
break;
}
//设置水印字体的位置
int yPixlesFromBottom = (int)(imgPhotoHeight * hScale);
float yPosFromBottom = ((imgPhotoHeight - yPixlesFromBottom) - (crSize.Height / 2));
float xCenterOfImg = (imgPhotoWidth * 1 / 2);
System.Drawing.StringFormat StrFormat = new System.Drawing.StringFormat();
StrFormat.Alignment = System.Drawing.StringAlignment.Center;
//画两次制造透明效果
System.Drawing.SolidBrush semiTransBrush2 = new System.Drawing.SolidBrush(Color.FromArgb(Alpha, 0, 0, 0));
gbmPhoto.DrawString(TextFont, crFont, semiTransBrush2, new System.Drawing.PointF(xCenterOfImg + 1, yPosFromBottom + 1), StrFormat);
System.Drawing.SolidBrush semiTransBrush = new System.Drawing.SolidBrush(Color.FromArgb(Alpha, 255, 255, 255));
gbmPhoto.DrawString(TextFont, crFont, semiTransBrush, new System.Drawing.PointF(xCenterOfImg, yPosFromBottom), StrFormat);
bmPhoto.Save(sImgPath, System.Drawing.Imaging.ImageFormat.Jpeg);
gbmPhoto.Dispose();
imgPhoto.Dispose();
bmPhoto.Dispose();
return true;
}
catch (Exception ex)
{
return false;
}
}
}
调用方法:
imgTextWater imgWater = new imgTextWater();
imgWater.TextWater(“d:\img\201029348485.jpg”, "水印的文字", “d:\img\201029348485.jpg”, 60,0.7f,0.55f);
OK了,这样图片就变成有水印文字了。
- 本文标题: ASP.NET上传图片添加文字水印,大小根据图片自动缩放长宽比例
- 文章分类:【.NET/Web】
- 非特殊说明,本文版权归【胡同里的砖头】个人博客 所有,转载请注明出处.