收藏一段小的.net下的验证码片段,以供以后参考。
protected void Page_Load(object sender, EventArgs e)
{
//先产生数字串
string checkCode = this.CreateRandomCode(6);
//用session保存
Session["CheckCode"] = checkCode;
//作图
CreateImage(checkCode);
}
private void CreateImage(string checkCode)
{
System.Drawing.Bitmap image = new System.Drawing.Bitmap(Convert.ToInt32(Math.Ceiling((decimal)(checkCode.Length * 14))), 22);
Graphics g = Graphics.FromImage(image);
try
{
Random random = new Random();
g.Clear(Color.AliceBlue);
for (int i = 0; i < 25; i++)
{
int x1 = random.Next(image.Width);
int x2 = random.Next(image.Width);
int y1 = random.Next(image.Height);
int y2 = random.Next(image.Height);
g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
}
Font font = new System.Drawing.Font("Comic Sans MS", 12, System.Drawing.FontStyle.Bold);
System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2f, true);
g.DrawString(checkCode, font, new SolidBrush(Color.Red), 2, 2);
for (int i = 0; i < 100; i++)
{
int x = random.Next(image.Width);
int y = random.Next(image.Height);
image.SetPixel(x, y, Color.FromArgb(random.Next()));
}
g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);
System.IO.MemoryStream ms = new System.IO.MemoryStream();
image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
Response.ClearContent();
Response.ContentType = "image/Gif";
Response.BinaryWrite(ms.ToArray());
}
finally
{
g.Dispose();
image.Dispose();
}
}
public string CreateRandomCode(int codeCount)
{
string allChar = "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[] allCharArray = allChar.Split(',');
string randomCode = "";
int temp = -1;
Random rand = new Random();
for (int i = 0; i < codeCount; i++)
{
if (temp != -1)
{
rand = new Random(i * temp * ((int)DateTime.Now.Ticks));
}
int t = rand.Next(36);
if (temp != -1 && temp == t)
{
return CreateRandomCode(codeCount);
}
temp = t;
randomCode += allCharArray[t];
}
return randomCode;
}
{
//先产生数字串
string checkCode = this.CreateRandomCode(6);
//用session保存
Session["CheckCode"] = checkCode;
//作图
CreateImage(checkCode);
}
private void CreateImage(string checkCode)
{
System.Drawing.Bitmap image = new System.Drawing.Bitmap(Convert.ToInt32(Math.Ceiling((decimal)(checkCode.Length * 14))), 22);
Graphics g = Graphics.FromImage(image);
try
{
Random random = new Random();
g.Clear(Color.AliceBlue);
for (int i = 0; i < 25; i++)
{
int x1 = random.Next(image.Width);
int x2 = random.Next(image.Width);
int y1 = random.Next(image.Height);
int y2 = random.Next(image.Height);
g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
}
Font font = new System.Drawing.Font("Comic Sans MS", 12, System.Drawing.FontStyle.Bold);
System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2f, true);
g.DrawString(checkCode, font, new SolidBrush(Color.Red), 2, 2);
for (int i = 0; i < 100; i++)
{
int x = random.Next(image.Width);
int y = random.Next(image.Height);
image.SetPixel(x, y, Color.FromArgb(random.Next()));
}
g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);
System.IO.MemoryStream ms = new System.IO.MemoryStream();
image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
Response.ClearContent();
Response.ContentType = "image/Gif";
Response.BinaryWrite(ms.ToArray());
}
finally
{
g.Dispose();
image.Dispose();
}
}
public string CreateRandomCode(int codeCount)
{
string allChar = "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[] allCharArray = allChar.Split(',');
string randomCode = "";
int temp = -1;
Random rand = new Random();
for (int i = 0; i < codeCount; i++)
{
if (temp != -1)
{
rand = new Random(i * temp * ((int)DateTime.Now.Ticks));
}
int t = rand.Next(36);
if (temp != -1 && temp == t)
{
return CreateRandomCode(codeCount);
}
temp = t;
randomCode += allCharArray[t];
}
return randomCode;
}
-------------------------第二个-------------------------
这个是页面的后台代码,只要建立好前台页面后把下面的代码拷贝过去就行了
在需要调用验证码的地方用下面这样的代码调用就行了
<img src="../PageControl/Security/ValidateCode.aspx?codeLen=5&aFineness=90&ImgWidth=85&PosX=4&PosY=1&FontFamily=Arial&FontSize=14&FontStyle=3"></img>
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
namespace VerCommunity.WebForum.PageCtrl.Security
{
/// <summary>
/// ValidateCode 验证码生成页
/// </summary>
public class ValidateCode : System.Web.UI.Page
{
// 验证码长度
private int codeLen=8;
// 图片清晰度
private int fineness=80;
// 图片宽度
private int imgWidth=128;
// 图片高度
private int imgHeight=24;
// 字体家族名称
private string fontFamily="Times New Roman";
// 字体大小
private int fontSize=14;
// 字体样式
private int fontStyle=0;
// 绘制起始坐标 X
private int posX=0;
// 绘制起始坐标 Y
private int posY=0;
//------------------------------------------------------------
// ValidateCode.aspx 页面加载函数
//------------------------------------------------------------
private void Page_Load(object sender, System.EventArgs e)
{
#region 读取 Request 传递参数
// 获取代码长度设置
if(Request["CodeLen"]!=null)
{
try
{
codeLen=Int32.Parse(Request["CodeLen"]);
// 规定验证码长度
if(codeLen<4 || codeLen>16)
throw new Exception("验证码长度必须在4到16之间");
}
catch(Exception Ex)
{
throw Ex;
}
}
// 获取图片清晰度设置
if(Request["Fineness"]!=null)
{
try
{
fineness=Int32.Parse(Request["Fineness"]);
// 验证清晰度
if(fineness<0 || fineness>100)
throw new Exception("图片清晰度必须在0到100之间");
}
catch(Exception Ex)
{
throw Ex;
}
}
// 获取图片宽度
if(Request["ImgWidth"]!=null)
{
try
{
imgWidth=Int32.Parse(Request["ImgWidth"]);
if(imgWidth<16 || imgWidth>480)
throw new Exception("图片宽度必须在16到480之间");
}
catch(Exception Ex)
{
throw Ex;
}
}
// 获取图片高度
if(Request["ImgHeight"]!=null)
{
try
{
imgWidth=Int32.Parse(Request["ImgHeight"]);
if(imgWidth<16 || imgWidth>320)
throw new Exception("图片高度必须在16到320之间");
}
catch(Exception Ex)
{
throw Ex;
}
}
// 获取验证码字体家族名称
if(Request["FontFamily"]!=null)
{
fontFamily=Request["FontFamily"];
}
// 获取验证码字体大小
if(Request["FontSize"]!=null)
{
try
{
fontSize=Int32.Parse(Request["FontSize"]);
if(fontSize<8 || fontSize>72)
throw new Exception("字体大小必须在8到72之间");
}
catch(Exception Ex)
{
throw Ex;
}
}
// 获取字体样式
if(Request["FontStyle"]!=null)
{
try
{
fontStyle=Int32.Parse(Request["FontStyle"]);
}
catch(Exception Ex)
{
throw Ex;
}
}
// 验证码绘制起始位置 X
if(Request["PosX"]!=null)
{
try
{
posX=Int32.Parse(Request["PosX"]);
}
catch(Exception Ex)
{
throw Ex;
}
}
// 验证码绘制起始位置 Y
if(Request["PosY"]!=null)
{
try
{
posY=Int32.Parse(Request["PosY"]);
}
catch(Exception Ex)
{
throw Ex;
}
}
#endregion
string validateCode=CreateValidateCode();
// 生成BITMAP图像
Bitmap bitmap=new Bitmap(imgWidth, imgHeight);
// 给图像设置干扰
DisturbBitmap(bitmap);
// 绘制验证码图像
DrawValidateCode(bitmap, validateCode);
// 保存验证码图像,等待输出
bitmap.Save(Response.OutputStream, ImageFormat.Gif);
}
#region Web 窗体设计器生成的代码
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
//
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.Load += new System.EventHandler(this.Page_Load);
}
#endregion
//------------------------------------------------------------
// 随机生成验证码,并保存到SESSION中
//------------------------------------------------------------
private string CreateValidateCode()
{
string validateCode="";
// 随机数对象
Random random=new Random();
for(int i=0; i<codeLen; i++)
{
// 26: a - z
int n=random.Next(26);
// 将数字转换成大写字母
validateCode+=(char)(n+65);
}
// 保存验证码
Session["ValidateCode"]=validateCode;
return validateCode;
}
//------------------------------------------------------------
// 为图片设置干扰点
//------------------------------------------------------------
private void DisturbBitmap(Bitmap bitmap)
{
// 通过随机数生成
Random random=new Random();
for(int i=0; i<bitmap.Width; i++)
{
for(int j=0; j<bitmap.Height; j++)
{
if(random.Next(100)<=this.fineness)
bitmap.SetPixel(i, j, Color.White);
}
}
}
//------------------------------------------------------------
// 绘制验证码图片
//------------------------------------------------------------
private void DrawValidateCode(Bitmap bitmap, string validateCode)
{
// 获取绘制器对象
Graphics g=Graphics.FromImage(bitmap);
// 设置绘制字体
Font font=new Font(fontFamily, fontSize, GetFontStyle());
// 绘制验证码图像
g.DrawString(validateCode, font, Brushes.Black, posX, posY);
}
//------------------------------------------------------------
// 换算验证码字体样式:1 粗体 2 斜体 3 粗斜体,默认为普通字体
//------------------------------------------------------------
private FontStyle GetFontStyle()
{
if(fontStyle==1)
return FontStyle.Bold;
else if(fontStyle==2)
return FontStyle.Italic;
else if(fontStyle==3)
return FontStyle.Bold | FontStyle.Italic;
else
return FontStyle.Regular;
}
}
}
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
namespace VerCommunity.WebForum.PageCtrl.Security
{
/// <summary>
/// ValidateCode 验证码生成页
/// </summary>
public class ValidateCode : System.Web.UI.Page
{
// 验证码长度
private int codeLen=8;
// 图片清晰度
private int fineness=80;
// 图片宽度
private int imgWidth=128;
// 图片高度
private int imgHeight=24;
// 字体家族名称
private string fontFamily="Times New Roman";
// 字体大小
private int fontSize=14;
// 字体样式
private int fontStyle=0;
// 绘制起始坐标 X
private int posX=0;
// 绘制起始坐标 Y
private int posY=0;
//------------------------------------------------------------
// ValidateCode.aspx 页面加载函数
//------------------------------------------------------------
private void Page_Load(object sender, System.EventArgs e)
{
#region 读取 Request 传递参数
// 获取代码长度设置
if(Request["CodeLen"]!=null)
{
try
{
codeLen=Int32.Parse(Request["CodeLen"]);
// 规定验证码长度
if(codeLen<4 || codeLen>16)
throw new Exception("验证码长度必须在4到16之间");
}
catch(Exception Ex)
{
throw Ex;
}
}
// 获取图片清晰度设置
if(Request["Fineness"]!=null)
{
try
{
fineness=Int32.Parse(Request["Fineness"]);
// 验证清晰度
if(fineness<0 || fineness>100)
throw new Exception("图片清晰度必须在0到100之间");
}
catch(Exception Ex)
{
throw Ex;
}
}
// 获取图片宽度
if(Request["ImgWidth"]!=null)
{
try
{
imgWidth=Int32.Parse(Request["ImgWidth"]);
if(imgWidth<16 || imgWidth>480)
throw new Exception("图片宽度必须在16到480之间");
}
catch(Exception Ex)
{
throw Ex;
}
}
// 获取图片高度
if(Request["ImgHeight"]!=null)
{
try
{
imgWidth=Int32.Parse(Request["ImgHeight"]);
if(imgWidth<16 || imgWidth>320)
throw new Exception("图片高度必须在16到320之间");
}
catch(Exception Ex)
{
throw Ex;
}
}
// 获取验证码字体家族名称
if(Request["FontFamily"]!=null)
{
fontFamily=Request["FontFamily"];
}
// 获取验证码字体大小
if(Request["FontSize"]!=null)
{
try
{
fontSize=Int32.Parse(Request["FontSize"]);
if(fontSize<8 || fontSize>72)
throw new Exception("字体大小必须在8到72之间");
}
catch(Exception Ex)
{
throw Ex;
}
}
// 获取字体样式
if(Request["FontStyle"]!=null)
{
try
{
fontStyle=Int32.Parse(Request["FontStyle"]);
}
catch(Exception Ex)
{
throw Ex;
}
}
// 验证码绘制起始位置 X
if(Request["PosX"]!=null)
{
try
{
posX=Int32.Parse(Request["PosX"]);
}
catch(Exception Ex)
{
throw Ex;
}
}
// 验证码绘制起始位置 Y
if(Request["PosY"]!=null)
{
try
{
posY=Int32.Parse(Request["PosY"]);
}
catch(Exception Ex)
{
throw Ex;
}
}
#endregion
string validateCode=CreateValidateCode();
// 生成BITMAP图像
Bitmap bitmap=new Bitmap(imgWidth, imgHeight);
// 给图像设置干扰
DisturbBitmap(bitmap);
// 绘制验证码图像
DrawValidateCode(bitmap, validateCode);
// 保存验证码图像,等待输出
bitmap.Save(Response.OutputStream, ImageFormat.Gif);
}
#region Web 窗体设计器生成的代码
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
//
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.Load += new System.EventHandler(this.Page_Load);
}
#endregion
//------------------------------------------------------------
// 随机生成验证码,并保存到SESSION中
//------------------------------------------------------------
private string CreateValidateCode()
{
string validateCode="";
// 随机数对象
Random random=new Random();
for(int i=0; i<codeLen; i++)
{
// 26: a - z
int n=random.Next(26);
// 将数字转换成大写字母
validateCode+=(char)(n+65);
}
// 保存验证码
Session["ValidateCode"]=validateCode;
return validateCode;
}
//------------------------------------------------------------
// 为图片设置干扰点
//------------------------------------------------------------
private void DisturbBitmap(Bitmap bitmap)
{
// 通过随机数生成
Random random=new Random();
for(int i=0; i<bitmap.Width; i++)
{
for(int j=0; j<bitmap.Height; j++)
{
if(random.Next(100)<=this.fineness)
bitmap.SetPixel(i, j, Color.White);
}
}
}
//------------------------------------------------------------
// 绘制验证码图片
//------------------------------------------------------------
private void DrawValidateCode(Bitmap bitmap, string validateCode)
{
// 获取绘制器对象
Graphics g=Graphics.FromImage(bitmap);
// 设置绘制字体
Font font=new Font(fontFamily, fontSize, GetFontStyle());
// 绘制验证码图像
g.DrawString(validateCode, font, Brushes.Black, posX, posY);
}
//------------------------------------------------------------
// 换算验证码字体样式:1 粗体 2 斜体 3 粗斜体,默认为普通字体
//------------------------------------------------------------
private FontStyle GetFontStyle()
{
if(fontStyle==1)
return FontStyle.Bold;
else if(fontStyle==2)
return FontStyle.Italic;
else if(fontStyle==3)
return FontStyle.Bold | FontStyle.Italic;
else
return FontStyle.Regular;
}
}
}
本文提供了一段ASP.NET下的验证码生成代码示例,包括验证码的生成、图像处理及输出等关键步骤。支持自定义验证码长度、清晰度、字体等。
527

被折叠的 条评论
为什么被折叠?



