C#生成随机验证码代码分享
使用yzmhelper帮助类即可
using system;
using system.web;
using system.drawing;
using system.security.cryptography;
namespace projectwendangmanage.framework
{
/// <summary>
/// 验证码类
/// </summary>
public class rand
{
#region 生成随机数字
/// <summary>
/// 生成随机数字
/// </summary>
/// <param name="length">生成长度</param>
public static string number(int length)
{
return number(length, false);
}
/// <summary>
/// 生成随机数字
/// </summary>
/// <param name="length">生成长度</param>
/// <param name="sleep">是否要在生成前将当前线程阻止以避免重复</param>
public static string number(int length, bool sleep)
{
if (sleep) system.threading.thread.sleep(3);
string result = "";
system.random random = new random();
for (int i = 0; i < length; i++)
{
result += random.next(10).tostring();
}
return result;
}
#endregion
#region 生成随机字母与数字
/// <summary>
/// 生成随机字母与数字
/// </summary>
/// <param name="intstr">生成长度</param>
public static string str(int length)
{
return str(length, false);
}
/// <summary>
/// 生成随机字母与数字
/// </summary>
/// <param name="length">生成长度</param>
/// <param name="sleep">是否要在生成前将当前线程阻止以避免重复</param>
public static string str(int length, bool sleep)
{
if (sleep) system.threading.thread.sleep(3);
char[] pattern = new char[] { '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 result = "";
int n = pattern.length;
system.random random = new random(~unchecked((int)datetime.now.ticks));
for (int i = 0; i < length; i++)
{
int rnd = random.next(0, n);
result += pattern[rnd];
}
return result;
}
#endregion
#region 生成随机纯字母随机数
/// <summary>
/// 生成随机纯字母随机数
/// </summary>
/// <param name="intstr">生成长度</param>
public static string str_char(int length)
{
return str_char(length, false);
}
/// <summary>
/// 生成随机纯字母随机数
/// </summary>
/// <param name="length">生成长度</param>
/// <param name="sleep">是否要在生成前将当前线程阻止以避免重复</param>
public static string str_char(int length, bool sleep)
{
if (sleep) system.threading.thread.sleep(3);
char[] pattern = new char[] { '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 result = "";
int n = pattern.length;
system.random random = new random(~unchecked((int)datetime.now.ticks));
for (int i = 0; i < length; i++)
{
int rnd = random.next(0, n);
result += pattern[rnd];
}
return result;
}
#endregion
}
/// <summary>
/// 验证图片类
/// </summary>
public class yzmhelper
{
#region 私有字段
private string text;
private bitmap image;
private int lettercount = 4; //验证码位数
private int letterwidth = 16; //单个字体的宽度范围
private int letterheight = 20; //单个字体的高度范围
private static byte[] randb = new byte[4];
private static rngcryptoserviceprovider rand = new rngcryptoserviceprovider();
private font[] fonts =
{
new font(new fontfamily("times new roman"),10 +next(1),system.drawing.fontstyle.regular),
new font(new fontfamily("georgia"), 10 + next(1),system.drawing.fontstyle.regular),
new font(new fontfamily("arial"), 10 + next(1),system.drawing.fontstyle.regular),
new font(new fontfamily("comic sans ms"), 10 + next(1),system.drawing.fontstyle.regular)
};
#endregion
#region 公有属性
/// <summary>
/// 验证码
/// </summary>
public string text
{
get { return this.text; }
}
/// <summary>
/// 验证码图片
/// </summary>
public bitmap image
{
get { return this.image; }
}
#endregion
#region 构造函数
public yzmhelper()
{
httpcontext.current.response.expires = 0;
httpcontext.current.response.buffer = true;
httpcontext.current.response.expiresabsolute = datetime.now.addseconds(-1);
httpcontext.current.response.addheader("pragma", "no-cache");
httpcontext.current.response.cachecontrol = "no-cache";
this.text = rand.number(4);
createimage();
}
#endregion
#region 私有方法
/// <summary>
/// 获得下一个随机数
/// </summary>
/// <param name="max">最大值</param>
private static int next(int max)
{
rand.getbytes(randb);
int value = bitconverter.toint32(randb, 0);
value = value % (max + 1);
if (value < 0) value = -value;
return value;
}
/// <summary>
/// 获得下一个随机数
/// </summary>
/// <param name="min">最小值</param>
/// <param name="max">最大值</param>
private static int next(int min, int max)
{
int value = next(max - min) + min;
return value;
}
#endregion
#region 公共方法
/// <summary>
/// 绘制验证码
/// </summary>
public void createimage()
{
int int_imagewidth = this.text.length * letterwidth;
bitmap image = new bitmap(int_imagewidth, letterheight);
graphics g = graphics.fromimage(image);
g.clear(color.white);
for (int i = 0; i < 2; i++)
{
int x1 = next(image.width - 1);
int x2 = next(image.width - 1);
int y1 = next(image.height - 1);
int y2 = next(image.height - 1);
g.drawline(new pen(color.silver), x1, y1, x2, y2);
}
int _x = -12, _y = 0;
for (int int_index = 0; int_index < this.text.length; int_index++)
{
_x += next(12, 16);
_y = next(-2, 2);
string str_char = this.text.substring(int_index, 1);
str_char = next(1) == 1 ? str_char.tolower() : str_char.toupper();
brush newbrush = new solidbrush(getrandomcolor());
point thepos = new point(_x, _y);
g.drawstring(str_char, fonts[next(fonts.length - 1)], newbrush, thepos);
}
for (int i = 0; i < 10; i++)
{
int x = next(image.width - 1);
int y = next(image.height - 1);
image.setpixel(x, y, color.fromargb(next(0, 255), next(0, 255), next(0, 255)));
}
image = twistimage(image, true, next(1, 3), next(4, 6));
g.drawrectangle(new pen(color.lightgray, 1), 0, 0, int_imagewidth - 1, (letterheight - 1));
this.image = image;
}
/// <summary>
/// 字体随机颜色
/// </summary>
public color getrandomcolor()
{
random randomnum_first = new random((int)datetime.now.ticks);
system.threading.thread.sleep(randomnum_first.next(50));
random randomnum_sencond = new random((int)datetime.now.ticks);
int int_red = randomnum_first.next(180);
int int_green = randomnum_sencond.next(180);
int int_blue = (int_red + int_green > 300) ? 0 : 400 - int_red - int_green;
int_blue = (int_blue > 255) ? 255 : int_blue;
return color.fromargb(int_red, int_green, int_blue);
}
/// <summary>
/// 正弦曲线wave扭曲图片
/// </summary>
/// <param name="srcbmp">图片路径</param>
/// <param name="bxdir">如果扭曲则选择为true</param>
/// <param name="nmultvalue">波形的幅度倍数,越大扭曲的程度越高,一般为3</param>
/// <param name="dphase">波形的起始相位,取值区间[0-2*pi)</param>
public system.drawing.bitmap twistimage(bitmap srcbmp, bool bxdir, double dmultvalue, double dphase)
{
double pi = 6.283185307179586476925286766559;
bitmap destbmp = new bitmap(srcbmp.width, srcbmp.height);
graphics graph = graphics.fromimage(destbmp);
graph.fillrectangle(new solidbrush(color.white), 0, 0, destbmp.width, destbmp.height);
graph.dispose();
double dbaseaxislen = bxdir ? (double)destbmp.height : (double)destbmp.width;
for (int i = 0; i < destbmp.width; i++)
{
for (int j = 0; j < destbmp.height; j++)
{
double dx = 0;
dx = bxdir ? (pi * (double)j) / dbaseaxislen : (pi * (double)i) / dbaseaxislen;
dx += dphase;
double dy = math.sin(dx);
int noldx = 0, noldy = 0;
noldx = bxdir ? i + (int)(dy * dmultvalue) : i;
noldy = bxdir ? j : j + (int)(dy * dmultvalue);
color color = srcbmp.getpixel(i, j);
if (noldx >= 0 && noldx < destbmp.width
&& noldy >= 0 && noldy < destbmp.height)
{
destbmp.setpixel(noldx, noldy, color);
}
}
}
srcbmp.dispose();
return destbmp;
}
#endregion
}
}
使用例子
//实例化yzmhelper
yzmhelper y = new yzmhelper();
//然后通过createimage()绘制验证码
y.createimage();
//通过y.text得到产生的验证码
tempdata["yzm"] = y.text;
//通过y.image得到产生的验证码图片
system.drawing.bitmap b = y.image;
//将验证码突破保存到知道路径下
b.save(path, system.drawing.imaging.imageformat.png);