ASP.NET实现验证码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
namespace UI._1209
{
public partial class 验证码 : System.Web.UI.Page
{
#region///自定义方法
#region/// 生成验证码图片 private void CreateCodeImage(string checkCode)
/// <summary>
/// 生成验证码图片
/// </summary>
private void CreateCodeImage(string checkCode)
{
//判断随机码是否存在
if (checkCode == null || checkCode.Trim() == String.Empty)
return;
int width=(int)Math.Ceiling((checkCode.Length * 12.5));//根据验证码设置画布的宽度
//设置画布的大小
Bitmap btmImg = new Bitmap(width, 22);
//创建画布
Graphics g = Graphics.FromImage(btmImg);
try
{
//创建随机数
Random random = new Random();
//设置画布的背景颜色
g.Clear(Color.White);
//设置背景噪音线
for (int i = 0; i < 2; i++)
{
int x1 = random.Next(btmImg.Width);
int y1 = random.Next(btmImg.Height);
int x2 = random.Next(btmImg.Width);
int y2 = random.Next(btmImg.Height);
g.DrawLine(new Pen(Color.Black), x1, y1, x2, y2);
}
//设置字体
Font font = new Font("宋体", 12f,FontStyle.Bold);
//设置文字的渐变颜色
LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, btmImg.Width, btmImg.Height), Color.Blue, Color.DarkRed, 1.2f, true);
//创建文字
g.DrawString(checkCode, font, brush, 2, 2);
//设置前景噪音点
for (int i = 0; i < 100; i++)
{
int x = random.Next(btmImg.Width);
int y = random.Next(btmImg.Height);
//随机生成噪音点并设置颜色
btmImg.SetPixel(x, y, Color.FromArgb(random.Next()));
}
//设置图片的边框线
g.DrawRectangle(new Pen(Color.Silver), 0, 0, btmImg.Width - 1, btmImg.Height - 1);
//创建内存流
MemoryStream ms = new MemoryStream();
//保存
btmImg.Save(ms,System.Drawing.Imaging.ImageFormat.Gif);
//清除流
Response.ClearContent();
//设置输出流的类型
Response.ContentType = "image/Gif";
//将其写入到输出流
Response.BinaryWrite(ms.ToArray());
}
finally
{
//回收画布资源
g.Dispose();
btmImg .Dispose();
}
}
#endregion
#region///生成验证码并将其保存到Cookies中 private string CreateCheckCode()
/// <summary>
/// 生成验证码并将其保存到Cookies中
/// </summary>
/// <returns>返回结果的字符串</returns>
private string CreateCheckCode()
{
int number;
char code;
string checkCode = String.Empty;
Random random = new Random();
for (int i = 0; i < 4; i++)
{
number = random.Next();
code = (char)('0' + (char)(number % 10));
checkCode += code.ToString();
}
Response.Cookies.Add(new HttpCookie("CheckCode", checkCode));
return checkCode;
}
#endregion
#endregion
protected void Page_Load(object sender, EventArgs e)
{
CreateCodeImage(CreateCheckCode());
}
}
}