水印是為了防止別盜用我們的圖片.
兩種方式實(shí)現(xiàn)水印效果
1)可以在用戶上傳時(shí)添加水印.
a) 好處:與2種方法相比,用戶每次讀取此圖片時(shí),服務(wù)器直接發(fā)送給客戶就行了.
b) 缺點(diǎn):破壞了原始圖片.
2)通過全局的一般處理程序,當(dāng)用戶請(qǐng)求這張圖片時(shí),加水印.
a) 好處:原始圖片沒有被破壞
b) 缺點(diǎn):用戶每次請(qǐng)求時(shí)都需要對(duì)請(qǐng)求的圖片進(jìn)行加水印處理,浪費(fèi)的服務(wù)器的資源.
代碼實(shí)現(xiàn)第二種方式:
復(fù)制代碼 代碼如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Drawing;
using System.IO;
namespace BookShop.Web
{
public class WaterMark : IHttpHandler
{
private const string WATERMARK_URL = "~/Images/watermark.jpg"; //水印圖片
private const string DEFAULTIMAGE_URL = "~/Images/default.jpg";span style="white-space:pre"> /span> //默認(rèn)圖片
#region IHttpHandler 成員
public bool IsReusable
{
get { return false; }
}
public void ProcessRequest(HttpContext context)
{
//context.Request.PhysicalPath //獲得用戶請(qǐng)求的文件物理路徑
System.Drawing.Image Cover;
//判斷請(qǐng)求的物理路徑中,是否存在文件
if (File.Exists(context.Request.PhysicalPath))
{
//加載文件
Cover = Image.FromFile(context.Request.PhysicalPath);
//加載水印圖片
Image watermark = Image.FromFile(context.Request.MapPath(WATERMARK_URL));
//通過書的封面得到繪圖對(duì)像
Graphics g = Graphics.FromImage(Cover);
//在image上繪制水印
g.DrawImage(watermark, new Rectangle(Cover.Width - watermark.Width, Cover.Height - watermark.Height,
[csharp] view plaincopy
watermark.Width, watermark.Height), 0, 0, watermark.Width, watermark.Height, GraphicsUnit.Pixel);
//釋放畫布
g.Dispose();
//釋放水印圖片
watermark.Dispose();
}
else
{
//加載默認(rèn)圖片
Cover = Image.FromFile(context.Request.MapPath(DEFAULTIMAGE_URL));
}
//設(shè)置輸出格式
context.Response.ContentType = "image/jpeg";
//將圖片存入輸出流
Cover.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
Cover.Dispose();
context.Response.End();
}
#endregion
}
}
您可能感興趣的文章:- asp.net中如何實(shí)現(xiàn)水印
- asp.net上傳圖片并作處理水印與縮略圖的實(shí)例代碼
- ASP.NET 圖片加水印防盜鏈實(shí)現(xiàn)代碼
- asp.net中上傳圖片文件實(shí)現(xiàn)防偽圖片水印并寫入數(shù)據(jù)庫
- asp.net 添加水印的代碼(已測(cè)試)
- 用ASP.NET實(shí)現(xiàn)簡(jiǎn)單的文字水印
- asp.net如何在圖片上加水印文字具體實(shí)現(xiàn)