[C#]生成验证码封装类

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.Collections;
using  System.Drawing;

/// <summary>
/// VerifyCode 的摘要说明
/// </summary>

public   class  VerifyCode
{
    
//产生随机字符串
    public string GenCode(int num)
    
{
        
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();
        
for(int i=0;i < num;i++)
        
{
            code 
+= source[rd.Next(0,source.Length)];
        }

        
return code;
    }


    
//生成图片
    public void GenImg(string code,Page curPage)
    
{
        Bitmap myPalette 
= new Bitmap(6020);//定义一个画板
        Graphics gh = Graphics.FromImage(myPalette);//在画板上定义绘图的实例
        Rectangle rc = new Rectangle(006020);//定义一个矩形
        gh.FillRectangle(new SolidBrush(Color.Blue), rc);//填充矩形
        gh.DrawString(code, new Font("宋体"16), new SolidBrush(Color.White), rc);//在矩形内画出字符串
        myPalette.Save(curPage.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);//将图片显示出来
        curPage.Session["ValidateCode"= code;//将字符串保存到Session中,以便需要时进行验证
        gh.Dispose();
        myPalette.Dispose();
    }

}

  GenCode()方法是用来生成验证码随机字符串 (int num 是需要生成验证码的位数)
GenImg()通过传入字符串,在页面上画出图片
-----
生成的随机字符串可以通过 session 或其他方法在页面间传值
此方法只能再一个单独的页面上画上一个验证码,然后在需要调用验证码的页面上<img>的src=""指向生成验证码图片的 aspx
比如:<asp:Image ID="LoginCodeImg" runat="server" ImageUrl="LoginCodeImage.aspx" />

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值