程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> .NET實例教程 >> asp.net 生成圖片驗證碼

asp.net 生成圖片驗證碼

編輯:.NET實例教程


identifyingcode.ASPx裡沒有內容略。
identifyingcode.cs文件:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
public partial class identifyingcode : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string tmp = RndNum(4);
        HttpCookie a = new HttpCookIE("ImageV", tmp);
        Response.CookIEs.Add(a);
        this.ValidateCode(tmp);

    }
    private void ValidateCode(string VNum)
    {
        Bitmap Img = null;
        Graphics g = null;
        MemoryStream ms = null;

        int gheight = VNum.Length * 12;
        Img = new Bitmap(gheight, 25);
        g = Graphics.FromImage(Img);
        //背景顏色 
        g.Clear(Color.LightSteelBlue);
        //文字字體 
        Font f = new Font("Arial Black", 10);
        //文字顏色 
        SolidBrush s = new SolidBrush(Color.RoyalBlue);
        g.DrawString(VNum, f, s, 3, 3);
        ms = new MemoryStream();
        Img.Save(ms, ImageFormat.Jpeg);
        Response.ClearContent();
        Response.ContentType = "images/Jpeg";
        Response.BinaryWrite(ms.ToArray());
        g.Dispose();
        Img.Dispose();
        Response.End();
    }

    private string RndNum(int VcodeNum)
    {
        string Vchar = "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[] VcArray = Vchar.Split(new Char[] { ',' });
        string VNum = "";
;   int temp = -1;

        Random rand = new Random();

        for (int i = 1; i < VcodeNum + 1; i++)
        {
            if (temp != -1)
            {
                rand = new Random(i * temp * unchecked((int)DateTime.Now.Ticks));
            }

            int t = rand.Next(35);
            if (temp != -1 && temp == t)
            {
                return RndNum(VcodeNum);
            }
            temp = t;
            VNum += VcArray[t];
        }
        return VNum;
    }

}
 
使用方法:
在需要它的頁面Html裡添加
 <img src="identifyingcode.ASPx" /> 
 

  HttpCookieCollection cookies = Request.CookIEs;
  string tmp = cookIEs["ImageV"].Value;
  然後比tmp與獲取的較驗證碼文本框中的值是否相同
 
出處:http://enuosky.cnblogs.com/archive/2006/05/15/400954.Html


     

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved