asp.net中浮水印的具體實現代碼_實用技巧

來源:互聯網
上載者:User

浮水印是為了防止別盜用我們的圖片.

兩種方式實現浮水印效果

1)可以在使用者上傳時添加浮水印.

a)   好處:與2種方法相比,使用者每次讀取此圖片時,伺服器直接發送給客戶就行了.

b)   缺點:破壞了原始圖片.

2)通過全域的一般處理常式,當使用者請求這張圖片時,加浮水印.

a)   好處:原始圖片沒有被破壞

b)   缺點:使用者每次請求時都需要對請求的圖片進行加浮水印處理,浪費的伺服器的資源.

代碼實現第二種方式:

複製代碼 代碼如下:

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>      //預設圖片  
        #region IHttpHandler 成員  

        public bool IsReusable  
        {  
            get { return false; }  
        }  

        public void ProcessRequest(HttpContext context)  
        {  

            //context.Request.PhysicalPath  //獲得使用者請求的檔案實體路徑  

            System.Drawing.Image Cover;  
            //判斷請求的實體路徑中,是否存在檔案  
            if (File.Exists(context.Request.PhysicalPath))  
            {  
                //負載檔案  
                Cover = Image.FromFile(context.Request.PhysicalPath);  
                //載入浮水印圖片  
                Image watermark = Image.FromFile(context.Request.MapPath(WATERMARK_URL));  
            //通過書的封面得到繪圖對像  
                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 
            {  
                //載入預設圖片  
                Cover = Image.FromFile(context.Request.MapPath(DEFAULTIMAGE_URL));  
            }  
            //設定輸出格式  
            context.Response.ContentType = "image/jpeg";  
            //將圖片存入輸出資料流  
            Cover.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);  
            Cover.Dispose();  
            context.Response.End();  
        }  

        #endregion  
    }  
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.