asp.net中验证码的实现 (转自http://blog.csdn.net/zhoufoxcn/archive/2007/07/19/1698615.aspx)

主要用到一个类,一个aspx页面,还有一个使用图片验证码的aspx页面。

随机图片生成类:

using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;

namespace Sooyie.Common
{
    
/// <summary>
    
/// 产生随即图片
    
/// </summary>
    public sealed class RandImage
    {
        
private const string RandCharString = "0123456789";
        
private int width;
        
private int height;
        
private int length;
        
/// <summary>
        
/// 默认构造函数,生成的图片宽度为48×24,随即字符串字符个数
        
/// </summary>
        public RandImage():this(48,24,4)
        {
        }
        
/// <summary>
        
/// 指定生成图片的宽和高,默认生成图片的字符串长度为4个字符
        
/// </summary>
        
/// <param name="width"></param>
        
/// <param name="height"></param>
        public RandImage(int width, int height):this(width,height,4)
        {
        }
        
/// <summary>
        
/// 指定生成图片的宽和高以及生成图片的字符串字符个数
        
/// </summary>
        
/// <param name="width"></param>
        
/// <param name="height"></param>
        
/// <param name="length"></param>
        public RandImage(int width, int height, int length)
        {
            
this.width = width;
            
this.height = height;
            
this.length = length;
        }
        
/// <summary>
        
/// 以默认的大小和默认的字符个数产生图片
        
/// </summary>
        
/// <returns></returns>
        public Image GetImage()
        {
            Bitmap image 
= new Bitmap(width, height);
            Graphics g 
= Graphics.FromImage(image);
            g.Clear(Color.White);
            
string randString = "";
            Random random
=new Random();
            
do
            {
                randString 
+= RandCharString.Substring(random.Next((int)DateTime.Now.Ticks)%RandCharString.Length, 1);
            }
            
while (randString.Length < 4);
            
float emSize=(float)width/randString.Length;
            Font font 
= new Font("Arial", emSize, (System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic));
            Pen pen 
= new Pen(Color.Silver);
            
#region 画图片的背景噪音线
            
int x1,y1,x2,y2;
            
            
for (int i = 0; i < 25; i++)
            {
                x1 
= random.Next(image.Width);
                y1 
= random.Next(image.Height);
                x2 
= random.Next(image.Width);
                y2 
= random.Next(image.Height);
                g.DrawLine(pen, x1, y1, x2, y2);
            }
            
#endregion

            
#region 画图片的前景噪音点
            
for (int i = 0; i < 100; i++)
            {
                x1 
= random.Next(image.Width);
                y1 
= random.Next(image.Height);
                image.SetPixel(x1, y1, Color.FromArgb(random.Next(Int32.MaxValue)));
            }
            
#endregion

            g.DrawString(randString, font, Brushes.Red, 
22);
            g.Dispose();
            
return image;
            
        }
    }
}

 将图片转换成html资源的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.IO;
using System.Drawing;
using System.Drawing.Imaging;
using Sooyie.Common;

public partial class CheckImage : System.Web.UI.Page
{
    
protected void Page_Load(object sender, EventArgs e)
    {
        
if (!Page.IsPostBack)
        {
            RandImage randImage
=new RandImage();
            System.Drawing.Image image 
= randImage.GetImage();
            System.IO.MemoryStream memoryStream 
= new MemoryStream();
            image.Save(memoryStream, ImageFormat.Jpeg);
            Response.ClearContent();
            Response.ContentType 
= "image/gif";
            Response.BinaryWrite(memoryStream.ToArray());
            image.Dispose();
            Response.End();
        }
    }
}

下面是怎么使用的例子:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Login.aspx.cs" Inherits="Admin_Login" %>

<!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 border="0" cellpadding="0" cellspacing="0" width="480">
        
<tr>
            
<td colspan="2" align="center">
                公文管理系统后台登陆
</td>
        
</tr>
        
<tr>
            
<td style=" 83px">
                用户名
</td><td>
                
<asp:TextBox ID="txtUserName" runat="server"></asp:TextBox>
                    
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="txtUserName"
                        ErrorMessage
="用户名"></asp:RequiredFieldValidator></td>
        
</tr>
        
<tr>
            
<td style="height: 19px;  83px;">
                密码
</td><td>
                
<asp:TextBox ID="txtPassword" runat="server" TextMode="Password"></asp:TextBox>
                    
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="txtPassword"
                        ErrorMessage
="密码"></asp:RequiredFieldValidator></td>
        
</tr>
        
<tr>
            
<td style="height: 19px;  83px;">
                校验码
</td><td>
                
<asp:TextBox ID="txtCheckCode" runat="server"></asp:TextBox><img src="CheckImage.aspx" alt="校验码" />
                    
<asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ControlToValidate="txtCheckCode"
                        ErrorMessage
="校验码必填"></asp:RequiredFieldValidator></td>
        
</tr>
        
<tr>
            
<td style=" 83px">
                
<asp:Button ID="btnLogin" runat="server" Text="登陆" OnClick="btnLogin_Click" /></td><td style=" 9px">
                    
<input id="Reset1" type="reset" value="清除" /></td>
        
</tr>
    
</table>
    
</div>
        
<asp:Literal ID="lStatus" runat="server" Visible="False"></asp:Literal>
    
</form>
</body>
</html>

请注意:<img src="CheckImage.aspx" alt="校验码" />这一句就使用了CheckImage.aspx.cs类中的功能,将图片通过HTTP输出。

原文地址:https://www.cnblogs.com/malaikuangren/p/1207103.html