建立一个Web窗体程序Captcha.aspx,其代码如下:
前台文件 Captcha.aspx:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Captcha.aspx.cs" Inherits="Captcha" %>
后台文件 Captcha.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.Design;
using System.Drawing;
public partial class Captcha : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
this.CreateImage();
this.Response.End();
}
/// <summary>
/// 字符串
/// </summary>
private string GetRand()
{
#region 字符串
string str = "";
//数字
for (int i = 0; i < 10; i++)
{
str += ((char)((char)'0' + (char)i)).ToString();
}
//字母
for (int i = 0; i < 26; i++)
{
str += ((char)((char)'a' + (char)i)).ToString();
str += ((char)((char)'A' + (char)i)).ToString();
}
#endregion
#region 重新排列字符串的顺序
Random rand = new Random();
string newStr = "";
do
{
if (str == null || str.Length < 1)
{
break;
}
int i = rand.Next(0, str.Length);
newStr += str[i].ToString();
str = str.Remove(i,1);
} while (true);
#endregion
str = newStr.Substring(rand.Next(0, newStr.Length - 4), 4);
this.Session.Add("CaptchaCode", str);
return str;
}
/// <summary>
/// 生成图片
/// </summary>
private void CreateImage()
{
string randCode = GetRand();
if (randCode == null || randCode.Trim() == String.Empty)
{
return;
}
System.Drawing.Bitmap image = new System.Drawing.Bitmap(80, 22);
Graphics g = Graphics.FromImage(image);
try
{
//生成随机生成器
Random random = new Random();
//清空图片背景色
g.Clear(Color.White);
//画图片的背景噪音线
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("Arial", 15, (System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic));
System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, image.Width - 20, image.Height), Color.Orange, Color.DarkRed, 1.2f, true);
g.DrawString(randCode, font, brush, 12, 0);
//画图片的前景噪音点
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();
}
}
}
注意:如果您的网页文件不是Captcha.aspx,请替换文件中的Captcha;如果您的文件类型不是网页文件(.aspx),请替换Response
将验证码图像<img style="width:80px; height:60px; border:0px" src="{src}" /> 中的{src}替换为Captcha.aspx的网址就OK了