asp.net验证码程序
作者:不详
[标签:图片]asp.net验证码程序
今天做了一个ASP.NET验证码生成程序,写出来和大家分享一下.
首选新建一个VerifyCode.aspx文件,这个文件里面不需要写东西.
在VerifyCode.aspx.cs写入下面的代码:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Drawing;
using System.Drawing.Drawing2D;
public partial class Admin_VerifyCode : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
String verifyCodeName;
verifyCodeName = Request["VerifyCodeName"];
if (String.IsNullOrEmpty(verifyCodeName))
{
verifyCodeName = "VerifyCodeName";
}
GenImg(GenCode(4), verifyCodeName);
}
//产生随机字符串
private string GenCode(int num)
{
string[] source ={ "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 code = "";
Random rd = new Random();
for (int i = 0; i < num; i++)
{
code += source[rd.Next(0, source.Length)];
}
return code;
}
//生成图片
private void GenImg(string code, string verifyCodeName)
{
Bitmap mypalette = new Bitmap(90, 20);//定义一个画板
Graphics gh = Graphics.FromImage(mypalette);//在画板上定义绘图的实例
try
{
Random rd = new Random();
Int32 fontSize;
Int32 rdX;
Int32 rdY;
gh.CompositingQuality = CompositingQuality.HighQuality;
//设置高质量插值法
gh.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
//设置高质量,低速度呈现平滑程度
gh.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
gh.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
Rectangle rc = new Rectangle(0, 0, 90, 20);//定义一个矩形
gh.FillRectangle(new SolidBrush((Color)new WebColorConverter().ConvertFromString("#6994C4")), rc);//填充矩形
Font Font;
Char[] arrChar=code.ToCharArray();
Color c = (Color)new WebColorConverter().ConvertFromString("#29528D");
Brush b = new SolidBrush(c);
for (Int32 i = 0; i < arrChar.Length; i++)
{
fontSize = rd.Next(11, 14);
Font = new Font("Arial", fontSize, FontStyle.Bold);
rdX = rd.Next(0, 3);
rdY = rd.Next(0, 5);
gh.DrawString(arrChar[i].ToString(), Font, b, i * 18 + rdX, rdY);//在矩形内画出字符串
}
mypalette.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);//将图片显示出来
Session[verifyCodeName] = code;//将字符串保存到session中,以便需要时进行验证
}
finally
{
gh.Dispose();
mypalette.Dispose();
}
}
}
最后只需要在引用的地方写上这样一句话,验证码就自动生成了.
<img src="../VerifyCode.aspx?VerifyCodeName=Admin_Login" width="90" height="20" />