C#生成验证码
GetBase64FromImage(int numbner) 为起始方法 number:验证码个数
#region 生成验证码
/// <summary>
/// 生成随机数
/// </summary>
/// 2016-08-04 zhuzq
/// <param name="CheckCodeLength">生成随机数长度</param>
/// <returns></returns>
public string RandNum(int CheckCodeLength)
{
int number;
char code;
string checkCode = String.Empty;
var random = new Random();
for (int i = 0; i < CheckCodeLength; i++)
{
number = random.Next();
//只要数字
if (number % 2 == 0)
{
code = (char)('0' + (char)(number % 10));
if (code == '0')//排除数字 0
{
i--;
continue;
}
}
else
{
code = (char)('A' + (char)(number % 26));
if (code == 'O')//排除字母 O
{
i--;
continue;
}
}
checkCode += code.ToString();
}
return checkCode;
}
/// <summary>
/// 根据字符串生成图片
/// </summary>
/// <param name="checkCode"></param>
/// <returns></returns>
private Bitmap CreateCheckCodeImage(string checkCode)
{
if (string.IsNullOrEmpty(checkCode))
{
return null;
}
try
{
var image = new Bitmap((int)Math.Ceiling((checkCode.Length * 12.5)), 22);
Graphics g = Graphics.FromImage(image);
//清空图片背景色
g.Clear(Color.White);
var font = new Font("Arial", 12, (FontStyle.Bold | FontStyle.Italic));
var brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height),Color.BlueViolet, Color.BlueViolet, 1.2f, true);
g.DrawString(checkCode, font, brush, 2, 2);
//画图片的边框线
g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);
var ms = new System.IO.MemoryStream();
image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
return image;
}
catch (Exception ex)
{
return null;
}
}
/// <summary>
/// 从base64字符串转为图片
/// </summary>
/// <param name="base64string"></param>
/// <returns></returns>
public Bitmap GetImageFromBase64(string base64string)
{
byte[] b = Convert.FromBase64String(base64string);
MemoryStream ms = new MemoryStream(b);
Bitmap bitmap = new Bitmap(ms);
return bitmap;
}
/// <summary>
/// 将图片转为base64字符串
/// </summary>
/// <returns></returns>
public string GetBase64FromImage(int CheckCodeLength)
{
string strbaser64 = "";
string CheckCodeNum = "";
try
{
CheckCodeNum = RandNum(CheckCodeLength);
var bmp = CreateCheckCodeImage(CheckCodeNum);
var ms = new MemoryStream();
bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
byte[] arr = new byte[ms.Length];
ms.Position = 0;
ms.Read(arr, 0, (int)ms.Length);
ms.Close();
strbaser64 = Convert.ToBase64String(arr);
}
catch (Exception ex)
{
throw new Exception("生成验证码图片转换时出错!");
}
return CheckCodeNum+"|"+strbaser64;
}
#endregion