新建一个verify.ashx用于输出一张图片
源码如下:
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.SessionState;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using Common;
namespace Diynic.Admin
{
/// <summary>
/// 生成验证码
/// </summary>
public class verify : IHttpHandler,IRequiresSessionState
{
private int letterWidth = 22; //单个字体的宽度范围
private int letterHeight = 25; //单个字体的高度范围
private int letterCount = 4; //验证码位数
private int lineCount = 6; //用于背景的噪音线条数
private int pointCount = 10; //用于前景的噪音点个数
private Font font = new Font("Arial", 13, FontStyle.Bold); //字体
//验证码的字符集,筛选掉了一些模糊字符
private char[] chars = "123456789ABCDEFGHJKMNPQRSTUVWXYZ".ToCharArray();
public void ProcessRequest(HttpContext context)
{
string code = GetRandomNumberString(letterCount);
context.Session["ran_id"] = code;
int imageWidth = code.Length * letterWidth;
//根据指定的宽高创建一个位图对象
Bitmap image = new Bitmap(imageWidth, letterHeight);
//从指定的位图创建绘图对象
Graphics g = Graphics.FromImage(image);
Random random = new Random();
Random newRandow = new Random();
g.Clear(Color.WhiteSmoke);
//画图片的背景噪音线
for (int i = 0; i < lineCount; i++)
{
//随机生成构成一条直线的两点坐标
int x1 = random.Next(image.Width);
int y1 = random.Next(image.Height);
int x2 = random.Next(image.Width);
int y2 = random.Next(image.Height);
g.DrawLine(new Pen(Color.MistyRose), x1, y1, x2, y2);
}
//画图片的前景噪音点
for (int i = 0; i < pointCount; 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.LightGray), 0, 0, image.Width - 1, image.Height - 1);
//内容
for (int i = 0; i < code.Length; i++)
{
string str = code.Substring(i, 1);
//画刷
Brush brush = new SolidBrush(GetRandomColor());
Point point = new Point(i * letterWidth + 1 + newRandow.Next(3), 1 + newRandow.Next(3));
g.DrawString(str, font, brush, point);
}
context.Response.Buffer = true;
context.Response.ExpiresAbsolute = System.DateTime.Now.AddSeconds(-1);
context.Response.Expires = 0;
context.Response.CacheControl="no-cache";
context.Response.AppendHeader("pragma","no-cache");
int count = StringHelper.StringToInt(q("r"));
//将验证码图片写入内存流,并将其以 "image/Png" 格式输出
MemoryStream ms = new MemoryStream();
try
{
image.Save(ms, ImageFormat.Png);
context.Response.ClearContent();
context.Response.ContentType = "image/Png";
context.Response.BinaryWrite(ms.ToArray());
}
finally
{
//显示释放资源
image.Dispose();
g.Dispose();
context.Response.End();
context.Session.Clear();
}
}
/// <summary>
/// 根据验证码位数生成随机字符串
/// </summary>
/// <param name="numberLength"></param>
/// <returns></returns>
public string GetRandomNumberString(int numberLength)
{
Random random = new Random();
string code = string.Empty;
for (int i = 0; i < numberLength; i++)
{
code += chars[random.Next(chars.Length)].ToString();
}
return code;
}
/// <summary>
/// 生成随机rgb颜色
/// </summary>
/// <returns></returns>
public Color GetRandomColor()
{
Random randomFirst = new Random((int)DateTime.Now.Ticks);
System.Threading.Thread.Sleep(randomFirst.Next(50));
Random randomSecond = new Random((int)DateTime.Now.Ticks);
//便于显示,生成深色rgb
int red = randomFirst.Next(256);
int green = randomSecond.Next(256);
int blue = ((red + green) > 400) ? 0 : (400 - red - green);
blue = (blue > 255) ? 255 : blue;
return Color.FromArgb(red, green, blue);
}
public string q(string s)
{
if (HttpContext.Current.Request.QueryString[s] != null && HttpContext.Current.Request.QueryString[s] != "")
{
return HttpContext.Current.Request.QueryString[s].ToString();
}
return string.Empty;
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
Demo:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="TestCode.aspx.cs" Inherits="Diynic.TestCode" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table>
<tbody>
<tr>
<td>验证码:</td>
<td><asp:TextBox ID="txtVerify" runat="server"></asp:TextBox></td>
<td><img id="verify" alt="验证码" src="Admin/verify.ashx" title="看不清?点击刷新" /></td>
</tr>
<tr>
<td colspan="3"><asp:Button ID="Submit" runat="server" Text="提交" OnClick="Submit_Click" /></td>
</tr>
</tbody>
</table>
</div>
</form>
</body>
<script type="text/javascript" src="js/jquery-1.4.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#verify").click(function () {
var rand = Math.random();
var where = "Admin/verify.ashx?r" + rand;
$(this).attr("src", where);
});
});
</script>
</html>
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Diynic
{
public partial class TestCode : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
}
}
protected void Submit_Click(object sender, EventArgs e)
{
string input=txtVerify.Text.Trim().ToUpper();
if (input == Session["ran_id"].ToString())
{
Response.Write("登录成功");
}
else
{
Response.Write("你输入的验证码有误,请重新输入");
}
}
}
}
已测试成功。
内容参考互联网,有删改。