教你製作簡單的驗證碼

來源:互聯網
上載者:User

        每次登入CSDN部落格都需要輸入驗證碼,有時候明明看著寫對了,卻是經常顯示驗證碼輸入錯誤。想著前一時間段剛學了如何產生和使用驗證碼,加之最近正在學習JS,所以在此總結一下驗證碼的產生和使用,增加常用代碼的積累,借鑒了牛腩的新聞發布系統。

        產生驗證碼代碼:

<%@ WebHandler Language="C#" Class="WaterMark" %>using System;using System.Web;using System.Drawing;using System.Drawing.Drawing2D;using System.Web.SessionState;  public class WaterMark : IHttpHandler, IRequiresSessionState  // 要使用session必須實現該介面,記得要匯入System.Web.SessionState命名空間{    public void ProcessRequest(HttpContext context)    {        string checkCode = GenCode(5);  // 產生5位隨機字元,可更改        context.Session["Code"] = checkCode; //將字串儲存到Session中,以便需要時進行驗證        System.Drawing.Bitmap image = new System.Drawing.Bitmap(120, 22);//定義驗證碼圖片的寬度和高度        Graphics g = Graphics.FromImage(image);        try        {            //產生隨機產生器            Random random = new Random();           //清空圖片背景色            g.Clear(Color.White);            // 畫圖片的背景雜音線            int i;            for (i = 0; i < 25; i++)            {                int x1 = random.Next(image.Width);                int x2 = random.Next(image.Width);                int y1 = random.Next(image.Height);                int y2 = random.Next(image.Height);                g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);            }             Font font = new System.Drawing.Font("Arial", 12, (System.Drawing.FontStyle.Bold));            System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2F, true);            g.DrawString(checkCode, font, brush, 2, 2);             //畫圖片的前景噪音點            g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);            System.IO.MemoryStream ms = new System.IO.MemoryStream();            image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);            context.Response.ClearContent();            context.Response.ContentType = "image/Gif";            context.Response.BinaryWrite(ms.ToArray());        }        finally        {            g.Dispose();            image.Dispose();        }    }    /// <summary>    /// 產生隨機字串    /// </summary>    /// <param name="num">隨機出幾個字元</param>    /// <returns>隨機出的字串</returns>    private string GenCode(int num)    {        string str = "廊坊師範學院提高班第八期李達";//圖片上出現的文字為這些之一,可重複        char[] chastr = str.ToCharArray();         // string[] source ={ "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "#", "$", "%", "&", "@" };        string code = "";          Random rd = new Random();        int i;        for (i = 0; i < num; i++)        {            //code += source[rd.Next(0, source.Length)];            code += str.Substring(rd.Next(0, str.Length), 1);        }        return code; }    public bool IsReusable    {        get        {            return false;        }    }}

        登入介面:

<p >驗證碼:<img src="../handler/WaterMark.ashx" id="vimg" alt="" onclick="changeCode()"/>

     使用JS避免瀏覽器緩衝問題:

     <script language="javascript" type="text/javascript">         function changeCode() {             var imgNode = document.getElementById("vimg");             imgNode.src = "../handler/WaterMark.ashx?t=" + (new Date()).valueOf();  // 這裡加個時間的參數是為了防止瀏覽器緩衝的問題            }      </script>

     登入介面後台代碼:

        // 判斷驗證碼是否輸入正確        string code = txtCode.Text.Trim().ToUpper();        string rightCode = Session["Code"].ToString();        if (code != rightCode)        {            Page.ClientScript.RegisterStartupScript(Page.GetType(), "message", "<script language='javascript' defer>alert('驗證碼輸入錯誤!');</script>");            return;        }

     運行介面:


        簡單介紹一下原理。首先是產生驗證圖片,在圖片上添加線和點等視覺噪音,在圖片上添加產生的字元,產生的驗證碼儲存在session["code"];為了避免緩衝問題,給驗證碼添加時間標記;使用時判斷輸入的字元與驗證碼字元是否相同即可。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.