在web应用程序中,如果上传的文件需要声明图片版权,添加水印,可以在.ashx 文件这样来做
.ashx 文件
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/hrml";
//接收FileUp.html text数据,打印输出
//context.Response.Write(context.Request.Form["txtName"]);
HttpPostedFile file = context.Request.Files[0];//获取上传的文件
if (file.ContentLength > 0)
{
//对上传的文件类型进行校验。
string fileName = Path.GetFileName(file.FileName);//获取上传文件的名称包含扩展名。
string fileExt = Path.GetExtension(fileName);//获取用户上传的文件扩展名
if (fileExt == ".jpg")
{
//1. 对上传文件进行重命名
string newfileName = Guid.NewGuid().ToString();
//2. 将上传的文件放在不同的目录下面
string dir = "/ImageUpload/" + DateTime.Now.Year + "/" + DateTime.Now.Month + "/" + DateTime.Now.Day + "/";
//创建文件夹
if (!Directory.Exists(context.Request.MapPath(dir)))
{
Directory.CreateDirectory(context.Request.MapPath(dir));
}
string fullDir = dir + newfileName + fileExt;//文件存放的完整路径。
file.SaveAs(context.Request.MapPath(fullDir));
//file.SaveAs(context.Request.MapPath("/ImageUpload/"+fileName));//保存已上传文件的内容
//创建图片的水印
//using (Image img = Image.FromStream(file.InputStream))
//根据上传成功的图片创建一个Image
using (Image img=Image.FromFile(context.Request.MapPath(fullDir)))
{
using (Bitmap map = new Bitmap(img.Width,img.Height)) //根据画布的高度与宽度创建画布。
{
//为画布创建画笔
using (Graphics g=Graphics.FromImage(map))
{
//用画笔在画布上画图,从画布的左上角开始,将整个图片画到画布上
g.DrawImage(img, 0, 0, img.Width, img.Height);
g.DrawString("创智播客", new Font("黑体", 14.0f, FontStyle.Bold), Brushes.Red, new PointF(map.Width - 70, map.Height - 25));
string waterImageName = "water_" + Guid.NewGuid().ToString();
map.Save(context.Request.MapPath("/ImageUpload/" + waterImageName + ".jpg"), System.Drawing.Imaging.ImageFormat.Jpeg);
context.Response.Write("<html><body><img src='/ImageUpload/"+waterImageName+".jpg'/></body></html>");//浏览器重新请求已上传的文件内容
}
}
}
}
else
{
context.Response.Write("只能上传图片文件");
}
}
else
{
context.Response.Write("请选择上传文件");
}
}