使用一般处理程序在已有图片上加水印或者写字
public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; //原图 System.Drawing.Bitmap bitmap = new Bitmap(context.Server.MapPath("Uploads/201307269946.jpg")); //水印图 System.Drawing.Bitmap bitmap1 = new Bitmap(context.Server.MapPath("Uploads/201307269390.png")); Graphics g = Graphics.FromImage(bitmap); //Drawing String //g.DrawString("www.cnblogs.com/g1mist", new Font("黑体", 30), Brushes.Red, new PointF(10, 60)); //Drawing Images //将水印图画在原图的(10,60)位置上 g.DrawImage(bitmap1, new Point(10, 60)); bitmap.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg); }
但是,一个一般处理程序一次在一张图片上加水印,如果需要在每一个对图片的请求中都对图片加上水印,那就要使用全局处理程序,新建一个类"WaterMarkHelper",并且实现IHttpHandler接口
public class WaterMarkHelper : IHttpHandler { public void ProcessRequest(HttpContext context) { //原始请求路径 string rawurl = context.Request.RawUrl; //取到物理路径 string path = context.Server.MapPath(rawurl); //取到水印的路径 string logoPath = context.Server.MapPath("201307269390.png"); //原图 using (Image img = Image.FromFile(path)) { //水印图 using (Image logoImage = Image.FromFile(logoPath)) { //原图为画板 using (Graphics g = Graphics.FromImage(img)) { //在原图上画上水印 g.DrawImage(logoImage, 10, 60, logoImage.Width, logoImage.Height); //保存图片 img.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg); } } } } public bool IsReusable { get { return false; } } }
接着在Web.config中进行配置:
.net 4.5:
<configuration> <system.web> <compilation debug="true" targetFramework="4.5" /> <httpRuntime targetFramework="4.5" /> </system.web> <system.webServer> <handlers> <add name="water" verb="*" path="Uploads/*.jpg" type="FileUpload.WaterMarkHelper"/> </handlers> </system.webServer> </configuration>
.net 4.0
<configuration> <system.web> <compilation debug="true" targetFramework="4.5" /> <httpRuntime targetFramework="4.5" /> <httpHandlers> <add verb="*" path="Uploads/*.jpg" type="FileUpload.WaterMarkHelper"/> </httpHandlers> </system.web> </configuration>
type: "命名空间.类名,程序集名称",如果没有命名空间就只写类名。和网站在同一个程序集就不用写程序及名称