通常處理程序處理圖片(動態給圖片加上水印、保存縮略圖、驗證碼)

       對網頁全部的圖片加水印的方式有 2 種:javascript

  1. 以破壞圖片的方式加上水印(這種方式的話,服務器端通常還有原圖的備份)
  2. 在圖片被請求時動態加上水印

 

文字水印

Html 頁面:html

<body>
    <!-- 圖片 src 屬性請求了一個服務器端的通常處理程序 -->
    <img src="AddWaterMarkDynamic.ashx?name=sky11.jpg" alt="" />
</body>

通常處理程序:java

public void ProcessRequest(HttpContext context)
{
    context.Response.ContentType = "image/jpeg";
    string msg = "Hello World!";
    string imgName = context.Request.QueryString["name"];
    if (!string.IsNullOrEmpty(imgName))
    {
        string imgPath = context.Server.MapPath("upload/image/" + imgName);
        using (Image img = Bitmap.FromFile(imgPath))
        {
            // 建立一個繪圖者,並指定繪製圖像
            using (Graphics g = Graphics.FromImage(img))
            {
                g.DrawString(msg, new Font("Verdana", 12, FontStyle.Bold), Brushes.Black, new PointF(5, 8));
                img.Save(context.Response.OutputStream, ImageFormat.Jpeg);
            }
        }
    }
}

效果:瀏覽器

image

 

 

圖片水印

public void ProcessRequest(HttpContext context)
{
    context.Response.ContentType = "image/jpeg";
    string msg = "Hello World!";
    string imgName = context.Request.QueryString["name"];
    if (!string.IsNullOrEmpty(imgName))
    {
        string imgPath = context.Server.MapPath("upload/image/" + imgName);
        using (Image img = Bitmap.FromFile(imgPath))
        {
            string water = context.Server.MapPath("upload/image/water.jpg");
            using (Image waterImg = Image.FromFile(water))
            {
                using (Graphics g = Graphics.FromImage(img))
                {
                    g.DrawImage(waterImg, (img.Width - waterImg.Width) / 2, (img.Height - waterImg.Height) / 2);
                    img.Save(context.Response.OutputStream, ImageFormat.Jpeg);
                }
            }
        }
    }
}

       此示例很簡單,可優化的部分有不少,好比重構成一個水印工廠類,來作到精確控制水印內容、位置、文字水印仍是圖片水印、透明度等等。緩存

 

 

保存縮略圖

       在接收到用戶上傳後的文件,若是文件類型是圖片類型,你在保存原圖的同時可能還須要保存一張縮略圖。服務器

public void ProcessRequest(HttpContext context)
{
    context.Response.ContentType = "text/html";
 
    HttpPostedFile file = context.Request.Files[0];
    if (file.ContentLength > 0)
    {
        string extName = Path.GetExtension(file.FileName);
        string fileName = Guid.NewGuid().ToString();
        string fullName = fileName + extName;
        string phyFilePath = context.Server.MapPath("~/Upload/Image/") + fullName;
        file.SaveAs(phyFilePath);
        context.Response.Write("上傳成功!文件名:" + fullName + "<br />");
 
        if (file.ContentType.Contains("image"))
        {
            context.Response.Write(string.Format("<img src='Upload/Image/{0}'/><br />", fullName));
            using (Image img = Bitmap.FromStream(file.InputStream))
            {
                using (Bitmap smallImg = new Bitmap(120, 40))
                {
                    using (Graphics g = Graphics.FromImage(smallImg))
                    {
                        g.DrawImage(img, new Rectangle(0, 0, smallImg.Width, smallImg.Height),
                            new Rectangle(0, 0, img.Width, img.Height), GraphicsUnit.Pixel);
                        smallImg.Save(context.Server.MapPath("~/Upload/Image/") + fileName + "_small" + extName);
                        context.Response.Write(string.Format("縮略圖保存成功!<br />"));
                        context.Response.Write(string.Format("<img src='Upload/Image/{0}'/><br />", (fileName + "_small" + extName)));
                    }
                }
            }
        }
    }
}

 

 

通常處理程序建立簡單的數字驗證碼圖片

       通常處理程序中要使用 Session 對象,必須實現一個標記接口:IRequiresSessionState 。微軟在後期的開發,對於標記都採用了 Attribute 屬性,但在開發 Session 時,仍是啓用了空的標記接口的作法。app

public class ValidateCode : IHttpHandler, IRequiresSessionState
{
    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "image/jpeg";
        string code = CreateRandomNumbers();
        context.Session["code"] = code;
        using (Bitmap img = new Bitmap(100, 40))
        {
            using (Graphics g = Graphics.FromImage(img))
            {
                g.DrawString(code, new Font("微軟雅黑", 16), Brushes.White, 15, 7);
                img.Save(context.Response.OutputStream, ImageFormat.Jpeg);
            }
        }
    }
 
    public string CreateRandomNumbers()
    {
        Random r = new Random();
        string str = string.Empty;
        for (int i = 0; i < 5; i++)
        {
            str += r.Next(10).ToString();
        }
        return str;
    }
 
    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

 

       在前臺頁面實現點擊圖片生成新的驗證碼效果,只需加上一小段 js 代碼,用來操縱圖片的 src 屬性便可(隨機數使瀏覽器的緩存機制失效):dom

<script type="text/javascript">
    window.onload = function () {
        document.getElementById("vCodeImg").onclick = function () {
            this.src = "ValidateCode.ashx?a=" + new Date();
        };
    }
</script>
相關文章
相關標籤/搜索