本文實例講述了asp.net繼承IHttpHandler接口實現給網站圖片添加水印功能。分享給大家供大家參考,具體如下:
先展示圖片效果:
1. 在App_Code下添加類文件,命名為ImageSY 文件內容如下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
|
public class ImageSY : IHttpHandler { public ImageSY() { // //TODO: 在此處添加構造函數邏輯 // } #region IHttpHandler 成員 public bool IsReusable { get { return true ; } } public void ProcessRequest(HttpContext context) { //獲得請求的物理圖片路徑 string imagePath = context.Request.PhysicalPath; System.Drawing.Image image = null ; if (File.Exists(imagePath)) { //定義水印文字 string text = "本圖片來至我的網站" ; //定義水印文字字體大小 int fontSize = 22; //水印文字字體 Font font = new Font( "宋體" , fontSize); //根據圖片物理地址加載圖片 image = System.Drawing.Image.FromFile(imagePath); Graphics g = Graphics.FromImage(image); //獲取要繪制水印文字所需要的顯示區域大小 SizeF size = g.MeasureString(text, font); if (size.Width > image.Width || size.Height > image.Height) { } else { Brush brush = Brushes.Red; g.DrawString(text, font, brush, image.Width - size.Width, image.Height - size.Height); g.Dispose(); } } else { } image.Save(context.Response.OutputStream, ImageFormat.Jpeg); } #endregion } |
2. 配置WebConfig,添加Location新節點
1
2
3
4
5
6
7
8
9
10
|
< location path = "images" > < system.web > < httpHandlers > <!---對jpg文件添加水印--> < add verb = "*" type = "ImageSY" path = "*.jpg" /> < add verb = "*" type = "ImageSY" path = "*.gif" /> < add verb = "*" type = "ImageSY" path = "*.bmp" /> </ httpHandlers > </ system.web > </ location > |
3. 測試,新建aspx頁面,顯示圖片,水印就會自動加上了
希望本文所述對大家asp.net程序設計有所幫助。