用一般处理程序做的。
第一种,使用非png格式的图片做水印图片。
非png格式的图片由于其背景色不是透明的,所以需要对其设置颜色矩阵,指定图片的颜色信息(变成透明状)。
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
// 获取访问上传数据的实例。
HttpPostedFile hpf = context.Request.Files["Filedata"];
if (hpf == null) return;
if (hpf.ContentLength == 0) return;
// 取出上传的图片
using (Image img = Image.FromStream(hpf.InputStream))
{
// 取出水印图片
using (Image waterimg = Image.FromFile(context.Request.MapPath("/Upload/2013/8/D41D8CD98F00B204E9800998ECF8427E_small.jpg")))
{
// 准备画笔,该画笔在上传的图片上“作画”
using (Graphics g = Graphics.FromImage(img))
{
// 使用Graphics DrawImage方法的第26个重载
// 参数1:指定画到上传的图片上的水印图片。
// 参数2:水印图片的位置
// 参数3-6:将水印图片的哪些位置画到上传的图片上(这里是水印图片的所有部分都画到上传图片上)
// 参数7:指定以上的数据的单位都是像素单位
// 参数8:指定图片的颜色信息。图片颜色的设置、调整、调亮、调暗。
g.DrawImage(waterimg, new Rectangle(img.Width - waterimg.Width, img.Height - waterimg.Height, waterimg.Width, waterimg.Height), 0, 0, waterimg.Width, waterimg.Height, GraphicsUnit.Pixel, setImgAttr(30));
// 文件命名
string name = Common.MD5.GetStreamMD5(hpf.InputStream);
string ext = Path.GetExtension(hpf.FileName);
string dic = "/Upload/" + DateTime.Now.Year + "/" + DateTime.Now.Month + "/";
Directory.CreateDirectory(Path.GetDirectoryName(context.Request.MapPath(dic)));
// 保存图片
img.Save(context.Request.MapPath(dic + name + ext));
// 输出图片路径、高度、宽度,前台接收,然后按高宽显示
context.Response.Write(dic + name + ext + ":" + img.Width + ":" + img.Height);
}
}
}
}
ImageAttributes setImgAttr(float ff)
{
// 颜色矩阵。RGBAW:红,绿,蓝,透明度,W。
float[][] f ={
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,ff/100f,0},
new float[]{0,0,0,0,1}
};
ColorMatrix cmf=new ColorMatrix(f);// 使用自己定义的颜色矩阵
ImageAttributes imgattr = new ImageAttributes();
// 使用自定义颜色矩阵调整图片的颜色。这里只设了透明度。
imgattr.SetColorMatrix(cmf, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
return imgattr;
}
第二种,直接使用png格式的图片来添加水印。
......
// 取出水印图片
using (Image waterimg = Image.FromFile(context.Request.MapPath("/Images/暗世界.png")))
{
// 准备画笔,该画笔在上传的图片上“作画”
using (Graphics g = Graphics.FromImage(img))
{
// 因为是png格式,故毋需准备颜色矩阵。
g.DrawImage(waterimg, img.Width - waterimg.Width, img.Height - waterimg.Height, waterimg.Width, waterimg.Height);
......
}
}