.net 生成随即验证码

呵呵。今天又学到新东西了。做了个随即的验证码。不是很好看。不过是那么回事!

基本原理

生成随即的字符串------建立个图片-------根据图片建立个画布-------在图片上随即画点点(噪点 )----------再把字符串画上去就OK了

using System;
using System.Data;
using System.Configuration;
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.IO;

/// <summary>
/// Code 的摘要说明
/// </summary>
public static class Code
{
    //public Code()
    //{
    //    //剑在心中(602730971.诚叫好友共同进步)
    //    // TODO: 在此处添加构造函数逻辑
    //    //
    //}
    //产生WNum位的随机数。剑在心中(602730971.诚叫好友共同进步)
    private static string Creatstring(int WNum)
    {
        string Str = "1,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f,g,h,i,j,k,l,m,n,p,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,P,P,Q,R,S,T,U,V,W,X,Y,Z";
        string[] Var = Str.Split(',');
        Random e = new Random();
        string Code="";
        for (int i = 0; i < WNum; i++)
        {
            int t = e.Next(61);
            Code += Var[t];
        }
        return Code;
    }
    //画图。剑在心中(602730971.诚叫好友共同进步)
    public static MemoryStream CreatCode(out string Code,int WNum)
    {
        Bitmap Img=null ;
        Graphics Grap=null ;
        MemoryStream wstream = new MemoryStream();
        Code= Creatstring(WNum).ToString();
        //颜色集合
        Color[] c = { Color.Black, Color.Red, Color.DarkBlue, Color.Green, Color.Orange, Color.Brown, Color.DarkCyan, Color.Purple };
        //字体集合
        string[] fonts ={ "Verdana", "Microsoft Sans Serif", "Comic Sans MS", "Arial", "宋体" };
        Random rand = new Random();
        Img = new Bitmap((int)WNum * 13 + 10, 32);
        Grap = Graphics.FromImage(Img);
        Grap.Clear(Color.White);
        //在Gaphics中画噪点.剑在心中(602730971.诚叫好友共同进步)
        for (int i = 0; i < 1000; i++)
        {
            int x = rand.Next(Img.Height);
            int y = rand.Next(Img.Width);
            //int P_x = rand.Next();
            //int P_y = rand.Next();
            int colorint = rand.Next(7);
            Grap.DrawRectangle(new Pen(Color.Moccasin), y, x,1, 1);
        }

        //在Graphics中画文字儿
        for(int i=0;i<WNum ;i++ )
        {
            int colIdx=rand.Next(7);
            int fonIdx=rand.Next(5);
            Font f=new Font(fonts[fonIdx],13,System.Drawing.FontStyle.Bold);
            Brush b=new System.Drawing.SolidBrush(c[colIdx]);
            Grap.DrawString(Code.Substring(i,1),f,b,5+i*12,9);
        }
        Img.Save(wstream,System.Drawing.Imaging.ImageFormat.Gif);
        return wstream;
    }

}

 

原文地址:https://www.cnblogs.com/cestbon/p/1662886.html