生成验证码
1、由字母和数字组成固定长度随机字符串
//得到随机字符串,长度暂限定为4
private string getRandomValidate()
{
int num;
int tem;
string rtuStr = "";
for (int i = 0; i < 2; i++)
{
num = ran.Next();
tem = num % 10 + '0';//生成数字
rtuStr += Convert.ToChar(tem).ToString();
num = ran.Next();
tem = num % 26 + 'A';//生成字符
rtuStr += Convert.ToChar(tem).ToString();
}
return rtuStr;
}
2、对所生成的字符串进行绘画、同时向画上画干扰线等
//生成图像
private void getImageValidate(string strValue)
{
//string str=oo00;前两个为字母o,后两个数为0
int width = Convert.ToInt32(strValue.Length * 20);
Bitmap img = new Bitmap(width, 30);
Graphics gfc = Graphics.FromImage(img);
gfc.Clear(Color.White);
drawLine(gfc, img);
//写验证码,要定义Font
Font font = new Font("arial", 18, FontStyle.Bold);
//Font font = new Font("宋体",12,FontStyle.Bold|FontStyle.Italic);
System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, img.Width, img.Height), Color.DarkOrchid, Color.Black, 1.5f, true);
gfc.DrawString(strValue, font, brush, 3, 2);
drawPoint(img);
gfc.DrawRectangle(new Pen(Color.DarkBlue), 0, 0, img.Width - 1, img.Height - 1);
//将图像添加到页面
MemoryStream ms = new MemoryStream();
img.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
//更改HTTP
Response.ClearContent();
Response.ContentType = "image/gif";
Response.BinaryWrite(ms.ToArray());
//Dispose
gfc.Dispose();
img.Dispose();
Response.End();
}
//划线
private void drawLine(Graphics gfc, Bitmap img)
{
//选择画10条线,也可以增加,也可以不要线,只要随机杂点就行
for (int i = 0; i < 10; i++)
{
int x1 = ran.Next(img.Width);
int y1 = ran.Next(img.Height);
int x2 = ran.Next(img.Width);
int y2 = ran.Next(img.Height);
gfc.DrawLine(new Pen(Color.Cyan), x1, y1, x2, y2);//注意画笔要淡,不然看不清
}
}
//画点
private void drawPoint(Bitmap img)
{
int col = ran.Next();//在一次的图片中杂点颜色相同
for (int i = 0; i < 100; i++)
{
int x = ran.Next(img.Width);
int y = ran.Next(img.Height);
img.SetPixel(x, y, Color.FromArgb(col));
}
}
3、将所生成的验证码字符串写入Session或Cookie中以便验证
string str= getRandomValidate();
Session["CheckCode"] = str;
4、在验证码显示处讲img标签的src属性设为生成验证码的页面
<img id="code" src="AdminCode.aspx" alt="" width="80" height="40" οndblclick="refreshCode()"/>
5、js刷新验证码时需将img标签的src属性设置为页面+随机数形式,如:code.aspx?New Date().getTime();以保证清空缓存每次都重新加载验证码达到刷新效果
<script type="text/javascript">
function refreshCode() {
$("#code").attr("src", "AdminCode.aspx?"+new Date().getTime());
}
</script>