验证码生成

#region 生成随机字符码
public string CreateVerifyCode(int codeLen)
{
if (codeLen == 0)
{
codeLen = Length;
}
string[] arr = CodeSerial.Split(',');
string code = "";
int randValue = -1;
Random rand = new Random(unchecked((int)DateTime.Now.Ticks));
for (int i = 0; i < codeLen; i++)
{
randValue = rand.Next(0, arr.Length - 1);
code += arr[randValue];
}
return code;
}


#endregion

#region 边框补(默认1像素)
int padding = 2;
public int Padding
{
get { return padding; }
set { padding = value; }
}
#endregion

#region 生成校验码图片
public Bitmap CreateImageCode(string code)
{
int fSize = FontSize;
int fWidth = fSize + Padding;
int imageWidth = (int)(code.Length * fWidth) + 5 + Padding * 2;
int imageHeight = fSize * 2 + Padding;
System.Drawing.Bitmap image = new System.Drawing.Bitmap(imageWidth, imageHeight);
Graphics g = Graphics.FromImage(image);
g.Clear(BackgroundColor);
Random rand = new Random();
//给背景添加随机生成的燥点
if (this.Chaos)
{
Pen pen = new Pen(ChaosColor, 0);
int c = Length * 9;
for (int i = 0; i < c; i++)
{
int x = rand.Next(image.Width);
int y = rand.Next(image.Height);
g.DrawRectangle(pen, x, y, 1, 1);
}
}
int left = 0, top = 0, top1 = 1, top2 = 1;
int n1 = (imageHeight - FontSize - Padding * 2);
int n2 = n1 / 4;
top1 = n2;
top2 = n2 * 2;
Font f;
Brush b;
int cindex, findex;
//随机字体和颜色的验证码字符
for (int i = 0; i < code.Length; i++)
{
cindex = rand.Next(Colors.Length - 1);
findex = rand.Next(Fonts.Length - 1);
f = new System.Drawing.Font(Fonts[findex], fSize, System.Drawing.FontStyle.Bold);
b = new System.Drawing.SolidBrush(Colors[cindex]);
if (i % 2 == 1)
{
top = top2;
}
else
{
top = top1;
}
left = i * fWidth;
g.DrawString(code.Substring(i, 1), f, b, left, top);
}
//画一个边框 边框颜色为Color.Gainsboro
g.DrawRectangle(new Pen(Color.Gainsboro, 0), 0, 0, image.Width - 1, image.Height - 1);
g.Dispose();
//产生波形(Add By 51aspx.com)
//image = TwistImage(image, true, 4, 4);
return image;
}
#endregion

原文地址:https://www.cnblogs.com/siaslfslovewp/p/4917373.html