客户要求在打印的时候背景上要有水印效果的文字,用来显示打印内容的发布时间等,程序如下:
代码
private string CreateWaterImg(string text)
{
string fileName = DateTime.Now.ToString("yyyyMMddhhmmss") + ".jpg";
// 已经存在的一个图片
string exsitImg = Server.MapPath(".") + "/Empty.jpg";
#region 文件夹(因为打印后无法及时删除,所以采用单双日文件夹删除前一天的方法)
string path = Server.MapPath(".") + "/WaterImg";
string path1 = Server.MapPath(".") + "/WaterImg";
if ((DateTime.Now.DayOfYear % 2) == 0)
{
path += "D";
path1 += "S";
}
else
{
path += "S";
path1 += "D";
}
DirectoryInfo curImgDir = new DirectoryInfo(path);
DirectoryInfo lastImgDir = new DirectoryInfo(path1);
if (!curImgDir.Exists)
{
curImgDir.Create();
}
if (lastImgDir.Exists)
{
lastImgDir.Delete(true);
}
#endregion
//加文字水印
System.Drawing.Image image = System.Drawing.Image.FromFile(exsitImg);
Graphics g = Graphics.FromImage(image);
g.DrawImage(image, 0, 0, image.Width, image.Height);
Font f = new Font("Verdana", 20, FontStyle.Italic);
// 后两个Color参数结合可以设置字体透明度
Brush b = new HatchBrush(HatchStyle.Percent30, Color.FromArgb(100, Color.Gray), Color.FromArgb(100, Color.Gray));
// 把当前图片上的内容清空
g.Clear(Color.White);
// 在图片上添加文字
for (int i = 10; i < image.Width ; i += 400)
{
for (int j = 0; j < image.Height - 80; j += 80)
{
{
string fileName = DateTime.Now.ToString("yyyyMMddhhmmss") + ".jpg";
// 已经存在的一个图片
string exsitImg = Server.MapPath(".") + "/Empty.jpg";
#region 文件夹(因为打印后无法及时删除,所以采用单双日文件夹删除前一天的方法)
string path = Server.MapPath(".") + "/WaterImg";
string path1 = Server.MapPath(".") + "/WaterImg";
if ((DateTime.Now.DayOfYear % 2) == 0)
{
path += "D";
path1 += "S";
}
else
{
path += "S";
path1 += "D";
}
DirectoryInfo curImgDir = new DirectoryInfo(path);
DirectoryInfo lastImgDir = new DirectoryInfo(path1);
if (!curImgDir.Exists)
{
curImgDir.Create();
}
if (lastImgDir.Exists)
{
lastImgDir.Delete(true);
}
#endregion
//加文字水印
System.Drawing.Image image = System.Drawing.Image.FromFile(exsitImg);
Graphics g = Graphics.FromImage(image);
g.DrawImage(image, 0, 0, image.Width, image.Height);
Font f = new Font("Verdana", 20, FontStyle.Italic);
// 后两个Color参数结合可以设置字体透明度
Brush b = new HatchBrush(HatchStyle.Percent30, Color.FromArgb(100, Color.Gray), Color.FromArgb(100, Color.Gray));
// 把当前图片上的内容清空
g.Clear(Color.White);
// 在图片上添加文字
for (int i = 10; i < image.Width ; i += 400)
{
for (int j = 0; j < image.Height - 80; j += 80)
{
// 这儿的处理时为了竖直对齐且为斜线
g.TranslateTransform(i, j);
g.RotateTransform(45);
g.DrawString(text, f, b, 0, 0);
g.RotateTransform(-45);
g.ResetTransform();
}
}
g.Dispose();
// 保存
string newPath = path + "/" + fileName;
image.Save(newPath);
image.Dispose();
// 返回相对路径
return newPath.Replace(Server.MapPath(".") + "/", "");
}
g.TranslateTransform(i, j);
g.RotateTransform(45);
g.DrawString(text, f, b, 0, 0);
g.RotateTransform(-45);
g.ResetTransform();
}
}
g.Dispose();
// 保存
string newPath = path + "/" + fileName;
image.Save(newPath);
image.Dispose();
// 返回相对路径
return newPath.Replace(Server.MapPath(".") + "/", "");
}
效果如下: