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);
}
}
}