.net的验证码

将自动生成的随机码赋给session["CheckCode"]。
然后将随机产生的数字显示在图片上。
        private void Page_Load(object sender, System.EventArgs e)
        
{
            
// 在此处放置用户代码以初始化页面

            
string checkCode=CreateRandomCode();
            Session[
"CheckCode"]=checkCode;
            CreateImage(checkCode);
        }

产生随机数的函数:
        private string CreateRandomCode()
        
{
            
//做个随机数库
            string allChar="0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,I,H,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z";
            
//将库里的字符放到数组里去
            string[] allCharArray=allChar.Split(',');
            
//定义RandomCode变量,为了存放生成的随机数。
            string RandomCode="";
            
int temp=-1;

            
//实例Random函数
            Random rand=new Random();
            
//for循环,这里是四次循环,为了是产生四个随机数,如果要产生多个,自己定义循环次数
            for(int i=0;i<4;i++)
            
{
                
if(temp!=-1)
                
{
                    
//在非第一次循环后执行这里,根据DataTime产生一个随机种子,用来计算伪随机数序列起始值的数字
                    rand=new Random(i*temp*((int)System.DateTime.Now.Ticks));
                }


                
//返回一个小于指定最大值的非负随机数
                int t=rand.Next(35);
                
if(temp==t)
                
{
                    
return CreateRandomCode();
                }

                temp
=t;
                
//将产生的值放入RandomCode变量中
                RandomCode+=allCharArray[t];
                
            }

            
//返回产生的随机字符串
            return RandomCode;
        }

    }

生成图片的函数:
        private void CreateImage(string RandomCode)
        
{
            
int iWidth;
            
//根据字符串的长度确定生成图片的宽度
            iWidth=(int)(RandomCode.Length*11.5);
            
//实例一个位图
            System.Drawing.Bitmap image=new Bitmap(iWidth,20);
            
//封装GDI+绘图面(此类无法继承)
            System.Drawing.Graphics g=Graphics.FromImage(image);
            
//实例文本格式,包括字体,字号,字形
            Font f=new Font("Arial",10,System.Drawing.FontStyle.Bold);
            
//实例填充图形形状
            System.Drawing.Brush b=new System.Drawing.SolidBrush(Color.Black);
            
//清楚整个绘图面并以指定背景色填充
            g.Clear(Color.White);
            
//绘制吧
            g.DrawString(RandomCode,f,b,3,3);

            
//创建一个内存流
            System.IO.MemoryStream ms=new System.IO.MemoryStream();
            
//将此图像以指定的格式保存到指定的流中
            image.Save(ms,System.Drawing.Imaging.ImageFormat.Jpeg);
            
//清楚缓存区流中的所有内容输出
            Response.ClearContent();
            
//设置输出流的HTTP MIME类型
            Response.ContentType="image/Jpeg";
            
//将一个二进制字符串写入HTTP输出流
            Response.BinaryWrite(ms.ToArray());
            
//释放资源
            g.Dispose();
            
//释放资源
            image.Dispose();
        }
原文地址:https://www.cnblogs.com/songafeng/p/123447.html