asp.net 验证码的方法和调用

本文介绍了一种使用C#生成包含随机字符的验证码图片的方法,并详细解释了如何设置图片大小、添加干扰线与点以及如何将字符绘制到图片上。
 
public byte[] GetImg(int keyLen,ref string strKey)
        {
            Random rd
=new Random((int)System.DateTime.Now.Ticks);

            
int widthImg=13*keyLen+5;
            
int heightImg = 25;
            System.Drawing.Bitmap  bmp 
= new System.Drawing.Bitmap(widthImg,heightImg);
            System.Drawing.Graphics graphics 
= System.Drawing.Graphics.FromImage(bmp);
            
//填充背景
            graphics.FillRectangle(new System.Drawing.SolidBrush(System.Drawing.Color.Black),0,0,widthImg,heightImg);

            
//噪音线
            int nLine = keyLen * 2;
            System.Drawing.Pen pen
= new System.Drawing.Pen(System.Drawing.Color.SkyBlue);
            
for (int i = 0; i < nLine; i ++)
            {
                
int x1 = rd.Next(widthImg);
                
int x2 = rd.Next(widthImg);
                
int y1 = rd.Next(heightImg);
                
int y2 = rd.Next(heightImg);
                graphics.DrawLine(pen,x1,y1,x2,y2);
            }
            
//验证码取值范围
            string strKeyFrom = "ABCDEFGHIJKNMPQRSTUVWXYZ23456789";
            
//验证字串获取,放入strResult和graphics
            string strResult = "";
            
for (int i = 0; i < keyLen; i ++)
            {
                
int x = (i * 13 + rd.Next(3));
                
int y = rd.Next(4)+1;

                
char c = strKeyFrom[rd.Next(strKeyFrom.Length)];//随即字符
                strResult = strResult + c.ToString();
                
//随即字符画入
                System.Drawing.Font font = new System.Drawing.Font("Arial",12 + rd.Next(1));
                graphics.DrawString(c.ToString(),font,
new System.Drawing.SolidBrush(System.Drawing.Color.White),x,y);
            }
            
//噪音点
            int nPixel = keyLen * 5;
            
for (int i = 0; i < nPixel; i ++)
            {
                
int x = rd.Next(widthImg);
                
int y = rd.Next(heightImg);
                bmp.SetPixel(x,y,System.Drawing.Color.SkyBlue);
            }
            
//输出
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            bmp.Save(ms,System.Drawing.Imaging.ImageFormat.Gif);
            
            strKey
=strResult;//获得验证码

            
byte[] byteAry = ms.ToArray();

            bmp.Dispose();
            graphics.Dispose();
            ms.Close();

            
return byteAry;
            
        }

调用

 

string strKey="";
            
byte[] gifByteAry=aa.GetImg(5,ref strKey);
            Session[
"strKey"]=strKey;//注意放入Session变量
            Response.OutputStream.Write(gifByteAry,0,gifByteAry.Length);//输出流直接写出,非文字
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值