天天看點

EF圖檔加水印

建立一個網站,準備其圖檔資源

添加Web頁面,展示圖檔

EF圖檔加水印

在網站中添加MyHandler類,繼承IHttpHandler接口,編寫加水印的功能

水印代碼如下:

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Web;

namespace WebApplication1
{
    public class MyHandler:IHttpHandler
    {
        public bool IsReusable => false;

        public void ProcessRequest(HttpContext context)
        {
            //得到使用者請求的圖檔
            String filename = context.Request.PhysicalPath;
            Bitmap bitmap = new Bitmap(filename);
            //執行個體化畫布
            Graphics graphics = Graphics.FromImage(bitmap);
            //在image上繪制水印
            graphics.DrawString("叼毛", new Font("宋體", 40, FontStyle.Bold), Brushes.Blue, new Point(0, 0));
            graphics.Flush();

            bitmap.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
        }
    }
}
           

在Web.config中配置實作當請求圖檔資源時由MyHandler類處理,配置如下:

<system.webServer>
  <handlers>
    <add name="m1" verb="*" path="Images/*" type="WebApplication1.MyHandler"/>
  </handlers>
</system.webServer>
           

功能實作:

EF圖檔加水印