使用通常處理程序在已有圖片上加水印或者寫字web
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中進行配置:url
.net 4.5:spa
<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.net
<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: "命名空間.類名,程序集名稱",若是沒有命名空間就只寫類名。和網站在同一個程序集就不用寫程序及名稱debug