页面添加验证码

来源:互联网 发布:数控喷丸机编程 编辑:程序博客网 时间:2024/05/21 06:27

CaptchaImage.cs(该文件用来制作显示的图片)

 using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Drawing.Text;

namespace CaptchaImage
{
 /// <summary>
 /// Summary description for CaptchaImage.
 /// </summary>
 public class CaptchaImage
 {
  // Public properties (all read-only).
  public string Text
  {
   get { return this.text; }
  }
  public Bitmap Image
  {
   get { return this.image; }
  }
  public int Width
  {
   get { return this.width; }
  }
  public int Height
  {
   get { return this.height; }
  }

  // Internal properties.
  private string text;
  private int width;
  private int height;
  private string familyName;
  private Bitmap image;

  // For generating random numbers.
  private Random random = new Random();

  // ====================================================================
  // Initializes a new instance of the CaptchaImage class using the
  // specified text, width and height.
  // ====================================================================
  public CaptchaImage(string s, int width, int height)
  {
   this.text = s;
   this.SetDimensions(width, height);
   this.GenerateImage();
  }

  // ====================================================================
  // Initializes a new instance of the CaptchaImage class using the
  // specified text, width, height and font family.
  // ====================================================================
  public CaptchaImage(string s, int width, int height, string familyName)
  {
   this.text = s;
   this.SetDimensions(width, height);
   this.SetFamilyName(familyName);
   this.GenerateImage();
  }

  // ====================================================================
  // This member overrides Object.Finalize.
  // ====================================================================
  ~CaptchaImage()
  {
   Dispose(false);
  }

  // ====================================================================
  // Releases all resources used by this object.
  // ====================================================================
  public void Dispose()
  {
   GC.SuppressFinalize(this);
   this.Dispose(true);
  }

  // ====================================================================
  // Custom Dispose method to clean up unmanaged resources.
  // ====================================================================
  protected virtual void Dispose(bool disposing)
  {
   if (disposing)
    // Dispose of the bitmap.
    this.image.Dispose();
  }

  // ====================================================================
  // Sets the image width and height.
  // ====================================================================
  private void SetDimensions(int width, int height)
  {
   // Check the width and height.
   if (width <= 0)
    throw new ArgumentOutOfRangeException("width", width, "Argument out of range, must be greater than zero.");
   if (height <= 0)
    throw new ArgumentOutOfRangeException("height", height, "Argument out of range, must be greater than zero.");
   this.width = width;
   this.height = height;
  }

  // ====================================================================
  // Sets the font used for the image text.
  // ====================================================================
  private void SetFamilyName(string familyName)
  {
   // If the named font is not installed, default to a system font.
   try
   {
    Font font = new Font(this.familyName, 12F);
    this.familyName = familyName;
    font.Dispose();
   }
   catch
   {
    this.familyName = System.Drawing.FontFamily.GenericSerif.Name;
   }
  }

  // ====================================================================
  // Creates the bitmap image.
  // ====================================================================
  private void GenerateImage()
  {
   // Create a new 32-bit bitmap image.
   Bitmap bitmap = new Bitmap(this.width, this.height, PixelFormat.Format32bppArgb);

   // Create a graphics object for drawing.
   Graphics g = Graphics.FromImage(bitmap);
   g.SmoothingMode = SmoothingMode.AntiAlias;
   Rectangle rect = new Rectangle(0, 0, this.width, this.height);

   // Fill in the background.
   HatchBrush hatchBrush = new HatchBrush(HatchStyle.SmallConfetti, Color.LightGray, Color.White);
   g.FillRectangle(hatchBrush, rect);

   // Set up the text font.
   SizeF size;
   float fontSize = rect.Height + 1;
   Font font;
   // Adjust the font size until the text fits within the image.
   do
   {
    fontSize--;
    font = new Font(this.familyName, fontSize, FontStyle.Bold);
    size = g.MeasureString(this.text, font);
   } while (size.Width > rect.Width);

   // Set up the text format.
   StringFormat format = new StringFormat();
   format.Alignment = StringAlignment.Center;
   format.LineAlignment = StringAlignment.Center;

   // Create a path using the text and warp it randomly.
   GraphicsPath path = new GraphicsPath();
   path.AddString(this.text, font.FontFamily, (int) font.Style, font.Size, rect, format);
   float v = 4F;
   PointF[] points =
   {
    new PointF(this.random.Next(rect.Width) / v, this.random.Next(rect.Height) / v),
    new PointF(rect.Width - this.random.Next(rect.Width) / v, this.random.Next(rect.Height) / v),
    new PointF(this.random.Next(rect.Width) / v, rect.Height - this.random.Next(rect.Height) / v),
    new PointF(rect.Width - this.random.Next(rect.Width) / v, rect.Height - this.random.Next(rect.Height) / v)
   };
   Matrix matrix = new Matrix();
   matrix.Translate(0F, 0F);
   path.Warp(points, rect, matrix, WarpMode.Perspective, 0F);

   // Draw the text.
   hatchBrush = new HatchBrush(HatchStyle.LargeConfetti, Color.DarkGreen, Color.DarkGreen);
   g.FillPath(hatchBrush, path);

   // Add some random noise.
   int m = Math.Max(rect.Width, rect.Height);
   for (int i = 0; i < (int) (rect.Width * rect.Height / 30F); i++)
   {
    int x = this.random.Next(rect.Width);
    int y = this.random.Next(rect.Height);
    int w = this.random.Next(m / 50);
    int h = this.random.Next(m / 50);
    g.FillEllipse(hatchBrush, x, y, w, h);
   }

   // Clean up.
   font.Dispose();
   hatchBrush.Dispose();
   g.Dispose();

   // Set the image.
   this.image = bitmap;
  }
 }
}
Controls/CaptchaImage/JpegImage.aspx(该文件验证码逻辑处理前台)

<%@ Page language="c#" Inherits="CaptchaImage.JpegImage" CodeFile="JpegImage.aspx.cs" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
 <HEAD>
  <title>JpegImage</title>
  <meta name="GENERATOR" Content="Microsoft Visual Studio 7.0">
  <meta name="CODE_LANGUAGE" Content="C#">
  <meta name="vs_defaultClientScript" content="JavaScript">
  <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
 </HEAD>
 <body>
  <form method="post" runat="server">
   <FONT face="宋体"></FONT>
  </form>
 </body>
</HTML>

Controls/CaptchaImage/JpegImage.aspx.cs(该文件验证码逻辑处理后台)

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 CaptchaImage
{
 public partial class JpegImage : System.Web.UI.Page
 {
  protected void Page_Load(object sender, System.EventArgs e)
  {
   // Create a CAPTCHA image using the text stored in the Session object.
   if(this.Session["CaptchaImageText"] != null)
   {
    CaptchaImage ci = new CaptchaImage(this.Session["CaptchaImageText"].ToString(), 100, 30, "Century Schoolbook");

    // Change the response headers to output a JPEG image.
    this.Response.Clear();
    this.Response.ContentType = "image/jpeg";

    // Write the image to the response stream in JPEG format.
    ci.Image.Save(this.Response.OutputStream, ImageFormat.Jpeg);

    // Dispose of the CAPTCHA image object.
    ci.Dispose();
   }
   else
   {
    Bis.Common.JSUtil.Alert(this, "验证码已过期");
   }
  }

  #region Web Form Designer generated code
  override protected void OnInit(EventArgs e)
  {
   //
   // CODEGEN: This call is required by the ASP.NET Web Form Designer.
   //
   InitializeComponent();
   base.OnInit(e);
  }
  
  /// <summary>
  /// Required method for Designer support - do not modify
  /// the contents of this method with the code editor.
  /// </summary>
  private void InitializeComponent()
  {   
  }
  #endregion
 }
}

Web/GuestBook.aspx(该页面中嵌入了验证码)

<%@ Page language="c#" Inherits="MyGuestBook.GuestBook" CodeFile="GuestBook.aspx.cs" %>
<HTML>
 <HEAD>
  <title>瑞虹新城</title>
  <meta http-equiv="Content-Type" content="text/html; charset=gb2312">
  <link href="css/new.css" rel="stylesheet" type="text/css">
 </HEAD>
 <body>
  <form id="form1" runat="server" method="post">
   <asp:validationsummary id="Validationsummary1" runat="server" DisplayMode="BulletList" EnableClientScript="true"
    ShowSummary="false" ShowMessageBox="true" HeaderText="请正确填写以下内容"></asp:validationsummary>
   <table width="484" border="0" align="center" cellpadding="0" cellspacing="0">
    <tr>
     <td><img src="images/online_ban.jpg" width="484" height="116"></td>
    </tr>
    <tr>
     <td height="22">&nbsp;</td>
    </tr>
   </table>
   <table width="400" border="0" align="center" cellpadding="0" cellspacing="0">
    <TBODY>
     <tr>
      <td>请认真填写下面的在线预约申请表格并确认信息的准确性,以方便我们及时<br>
       为您提供准确购房信息。谢谢您的参与!</td>
     </tr>
     <tr>
      <td height="25">&nbsp;</td>
     </tr>
     <tr>
      <td>
       <table width="100%" border="0" cellspacing="0" cellpadding="3">
        <TBODY>
         <tr>
          <td width="19%">姓 名:</td>
          <td width="81%">
           <asp:TextBox id="txtName" runat="server" Width="200px"></asp:TextBox>
           <asp:requiredfieldvalidator id="RequiredFieldValidator" runat="server" ControlToValidate="txtName" ErrorMessage="姓名必须填写"
            Display="None" />
           <asp:regularexpressionvalidator id="RegularExpressionValidator" runat="server" ControlToValidate="txtName" ErrorMessage="姓名名不能有'字符"
            Display="None" ValidationExpression="[^']+"></asp:regularexpressionvalidator>
          </td>
         </tr>
         <tr>
          <td>年 龄:</td>
          <td>
           <asp:TextBox id="txtAge" runat="server" Width="200px"></asp:TextBox>
           <asp:requiredfieldvalidator id="Requiredfieldvalidator3" runat="server" ControlToValidate="txtAge" ErrorMessage="年龄必须填写"
            Display="None"></asp:requiredfieldvalidator>
           <asp:regularexpressionvalidator id="Regularexpressionvalidator2" runat="server" ControlToValidate="txtAge" ErrorMessage="请填写正确的年龄"
            Display="None" ValidationExpression="^(1[0-9]/d|/d{1,2})$"></asp:regularexpressionvalidator>
          </td>
         </tr>
         <tr>
          <td>联系电话:</td>
          <td>
           <asp:TextBox id="txtTel" runat="server" Width="200px"></asp:TextBox>
           <asp:requiredfieldvalidator id="Requiredfieldvalidator1" runat="server" ControlToValidate="txtTel" ErrorMessage="联系电话必须填写"
            Display="None" />
           <asp:regularexpressionvalidator id="Regularexpressionvalidator1" runat="server" ControlToValidate="txtTel" ErrorMessage="联系电话名不能有'字符"
            Display="None" ValidationExpression="[^']+"></asp:regularexpressionvalidator>
          </td>
         </tr>
         <tr>
          <td>电子信箱:</td>
          <td>
           <asp:TextBox id="txtEmail" runat="server" Width="300px"></asp:TextBox>
           <asp:requiredfieldvalidator id="Requiredfieldvalidator2" runat="server" ControlToValidate="txtEmail" ErrorMessage="电子信箱必须填写"
            Display="None" />
           <asp:regularexpressionvalidator id="Regularexpressionvalidator3" runat="server" ControlToValidate="txtEmail" ErrorMessage="请填写正确的邮箱地址"
            Display="None" ValidationExpression="/w+([-+.]/w+)*@/w+([-.]/w+)*/./w+([-.]/w+)*"></asp:regularexpressionvalidator>
          </td>
         </tr>
         <tr>
          <td valign="top">留 言:</td>
          <td>
           <asp:TextBox id="txtMessage" runat="server" Width="300px" TextMode="MultiLine" Rows="7"></asp:TextBox>
           <asp:requiredfieldvalidator id="Requiredfieldvalidator4" runat="server" ControlToValidate="txtMessage" ErrorMessage="留言必须填写"
            Display="None" />
           <asp:regularexpressionvalidator id="Regularexpressionvalidator4" runat="server" ControlToValidate="txtMessage" ErrorMessage="请填写正确的留言"
            Display="None" ValidationExpression="[^']+"></asp:regularexpressionvalidator>
          </td>
         </tr>
         <tr>
          <td>&nbsp;</td>
          <td><asp:button id="btnSubmit" runat="server" CssClass="bn" text="提 交" onclick="btnSubmit_Click" />
           &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <input type="reset" value="重 填" class="bn">
          </td>
         </tr>
        </TBODY>
       </table>
      </td>
     </tr>
    </TBODY>
   </table>
   <table width="484" border="0" align="center" cellpadding="0" cellspacing="0">
    <tr>
     <td height="27">&nbsp;</td>
    </tr>
    <tr>
     <td height="40" align="right" bgcolor="#f4f4f4"><img src="images/online_copyright.gif" width="153" height="28"></td>
    </tr>
   </table>
   
  </form>
 </body>
</HTML>
Web/GuestBook.aspx.cs(验证码判断)

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace MyGuestBook
{
 /// <summary>
 /// GuestBook 的摘要说明。
 /// </summary>
 public partial class GuestBook : System.Web.UI.Page
 {
  protected System.Web.UI.WebControls.Button btnReset;
 
  protected void Page_Load(object sender, System.EventArgs e)
  {
   // 在此处放置用户代码以初始化页面
  }

  #region Web 窗体设计器生成的代码
  override protected void OnInit(EventArgs e)
  {
   //
   // CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
   //
   InitializeComponent();
   base.OnInit(e);
  }
  
  /// <summary>
  /// 设计器支持所需的方法 - 不要使用代码编辑器修改
  /// 此方法的内容。
  /// </summary>
  private void InitializeComponent()
  {   

  }
  #endregion

  protected void btnSubmit_Click(object sender, System.EventArgs e)
  {
   string name = Bis.Common.PageValidate.HtmlEncode(txtName.Text);
   int age = int.Parse(txtAge.Text);
   string tel = Bis.Common.PageValidate.HtmlEncode(txtTel.Text);
   string email = Bis.Common.PageValidate.HtmlEncode(txtEmail.Text);
   string message = Bis.Common.PageValidate.HtmlEncode(txtMessage.Text);
   DateTime adddate = DateTime.Now;
   Bis.Model.GuestBook items = new Bis.Model.GuestBook(0, name, age, tel, email, message, "", adddate);
   Bis.BLL.Gbook gbook = new Bis.BLL.Gbook();
   if (gbook.Insert(items))
   {
    Response.Redirect("online_ok.htm");
   }
   else
   {
    Bis.Common.JSUtil.Alert(this, "提交失败");
   }
   
  
  }

 }
}

 

Reservation.aspx  

Reservation.aspx.cs 
Controls/CaptchaImage/JpegImage.aspx         
Controls/CaptchaImage/JpegImage.aspx.cs      
App_Code/Controls/CaptchaImage/CaptchaImage.cs

原创粉丝点击