ASP.NET中怎么为图片增加水印文字
发布时间:2023-05-17 02:49:50
在ASP.NET中,为图片添加水印文字是一项非常常见的需求。这个需求可以通过一些简单的代码来实现。本篇文章将分享如何通过ASP.NET代码来为图片增加水印文字。
1. 获取图片
首先,我们需要获取需要添加水印的图片。 可以通过以下代码来实现。
// 获取指定路径下的图片
string imagePath = Server.MapPath("~/images/example.jpg");
System.Drawing.Image image = System.Drawing.Image.FromFile(imagePath);
2. 创建画布和文字
接下来,我们需要创建一个画布并在画布中绘制我们要添加的文字。 可以使用以下代码来实现:
// 创建一个Bitmap对象
Bitmap bitmap = new Bitmap(image.Width, image.Height + 50);
// 创建Graphics对象
Graphics graphics = Graphics.FromImage(bitmap);
// 在画布上绘制原始图片
graphics.DrawImage(image, new Rectangle(0, 0, image.Width, image.Height));
// 设置字体颜色、大小、样式
Font font = new Font("Arial", 20, FontStyle.Bold);
// 添加水印文字
graphics.DrawString("My Watermark", font, Brushes.White, new PointF(10, image.Height + 10));
3. 保存图片
最后,我们需要将添加了水印文字的图片保存。可以使用以下代码保存图片。
// 保存添加水印的图片
string savePath = Server.MapPath("~/images/example_watermark.jpg");
bitmap.Save(savePath, ImageFormat.Jpeg);
完整代码
下面是完整的添加水印文字的ASP.Net代码:
// 获取指定路径下的图片
string imagePath = Server.MapPath("~/images/example.jpg");
System.Drawing.Image image = System.Drawing.Image.FromFile(imagePath);
// 创建一个Bitmap对象
Bitmap bitmap = new Bitmap(image.Width, image.Height + 50);
// 创建Graphics对象
Graphics graphics = Graphics.FromImage(bitmap);
// 在画布上绘制原始图片
graphics.DrawImage(image, new Rectangle(0, 0, image.Width, image.Height));
// 设置字体颜色、大小、样式
Font font = new Font("Arial", 20, FontStyle.Bold);
// 添加水印文字
graphics.DrawString("My Watermark", font, Brushes.White, new PointF(10, image.Height + 10));
// 保存添加水印的图片
string savePath = Server.MapPath("~/images/example_watermark.jpg");
bitmap.Save(savePath, ImageFormat.Jpeg);
