网络验证码的生成

此博客展示了用于网络验证码生成的代码。定义了AuthCode类,包含生成验证码的方法GenerateAuthCode,可指定长度、是否包含数字和字符等,还能将验证码字符串转换为图片流,通过ConvertStr2Img方法实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

using System;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;

namespace WindowsApplication1
{
 /// <summary>
 /// 用于网络验证码的生成
 /// </summary>
 public class AuthCode
 {
  public AuthCode()
  {
  }

  /// <summary>
  /// 产生验证码
  /// </summary>
  public static string GenerateAuthCode(int Length, bool IncNumber, bool IncChar, int ImgWidth,int ImgHeight,out string RetString, ref Graphics g)
  {

   if(Length>32)
   {
    RetString = "length too long";
    return "";
   }

   if(!IncChar && !IncNumber)
   {
    RetString = "must include number or char";
    return "";
   }

   byte [] arrB = new byte[32];

   Random r = new Random();
   int i = 0;
   byte _b = (byte)r.Next(48,122);

   while(i<Length)
   {
    if(!(!IncNumber && _b<=57) && !(!IncChar && _b>57))
    {
     if(!((_b>=58 && _b<=64) || (_b>=91 && _b<=96)))
     {
      arrB[i]=_b;i++;
     }
    }
    _b = (byte)r.Next(48,122); 
   }

   char [] arrC = new char[32];

   ASCIIEncoding ae = new ASCIIEncoding();
   Decoder de = ae.GetDecoder();
   de.GetChars(arrB,0,Length,arrC,0);

   RetString = new string(arrC);

   ConvertStr2Img(ImgWidth,ImgHeight,RetString,ref g);

   return Guid.NewGuid().ToString();

  }
  /// <summary>
  /// 产生验证码
  /// </summary>
  public static string GenerateAuthCode(out string RetString, ref Graphics g)
  {
   return GenerateAuthCode(4,true,true,80,20,out RetString,ref g);
  }

  /// <summary>
  /// 根据字符串获得图片流
  /// </summary>
  public static void ConvertStr2Img(int ImgWidth,int ImgHeight,string CodeString,ref Graphics g)
  {   
   if(null == g)return;

   RectangleF lRect = new RectangleF(0,0,(float)ImgWidth,(float)ImgHeight);
   Font _f = new Font("Arial",ImgHeight-4,GraphicsUnit.Pixel);
   g.FillRectangle(Brushes.White,0,0,ImgWidth,ImgHeight);
   g.DrawString(CodeString,_f,Brushes.Black,lRect);

  }
 }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值