新建一个Handler.ashx 的文件直接copy下面的代码:
public class AddWaterPic : IHttpHandler
{
public AddWaterPic()
{
//
//TODO: 在此处添加构造函数逻辑
//
}
private const string LOGO = "~/Logo.png"; //水印图片
private readonly float ALPHA = 1.0f; //透明度
/// <summary>
/// 指示IHttpHandler 实例是否可再次使用
/// </summary>
public bool IsReusable
{
get { return true; }
}
public void ProcessRequest(HttpContext context)
{ //获取请求的物理图片路径
if (context.Request.QueryString["u"] != null)
{
string imgSrc = context.Request.QueryString["u"];
string imagePath = context.Server.MapPath("~/Upload/BigPic/" + imgSrc);
System.Drawing.Image image = null;
if (File.Exists(imagePath))
{
image = new Bitmap(imagePath);
System.Drawing.Image images = Drawing(image, context.Server.MapPath(LOGO));
context.Response.ContentType = "image/jpeg";//输出图片的类型
images.Save(context.Response.OutputStream, ImageFormat.Jpeg);//将添加水印的图片输入到当前流中
image.Dispose();
}
context.Response.End();
}
}
//给图片添加水印
private System.Drawing.Image Drawing(System.Drawing.Image image, string logo)
{
Graphics g = Graphics.FromImage(image); //获得Graphics 对象
System.Drawing.Image watermark = System.Drawing.Image.FromFile(logo);//将水印图片放入watermark 对象
//关于透明度(使用颜色矩阵)
float[][] nArray ={ new float[] {1, 0, 0, 0, 0},
new float[] {0, 1, 0, 0, 0},
new float[] {0, 0, 1, 0, 0},
new float[] {0, 0, 0,ALPHA , 0},
new float[] {0, 0, 0, 0, 1}};
ColorMatrix colormatrix = new ColorMatrix(nArray);
ImageAttributes attributes = new ImageAttributes();
attributes.SetColorMatrix(colormatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
g.DrawImage(watermark, new Rectangle(image.Width - watermark.Width - 20, image.Height - watermark.Height - 15,
watermark.Width, watermark.Height), 0, 0, watermark.Width, watermark.Height, GraphicsUnit.Pixel, attributes);//在图片指定坐标处放入一个矩形图片内容为水印图片
g.Dispose();
watermark.Dispose();
return image;
}
}
2.在web.config中记得配置 <add verb="*" type="Handler的名" path="自己命名"/> <remove verb="*" path="*.asmx"/>例如:
<add verb="*" type="AddWaterPic" path="WaterImgs"/>
<remove verb="*" path="*.asmx"/>
在调用的时候:this.imgUrl.ImageUrl = "WaterImgs?u=" + pic.PImgpath;
这种加水印的方法好在不修改原来的图片~很好用的~