ASP.NET图片验证码的实现

ASP.NET     图文 验证码

          虽然我认为图片验证码没有什么用,并且也特别的烦人(每次上移动的网站都要频频地输入验证码),但人家要求,也只好弄一个。

          生成图片验证码页面createImg.aspx,验证页面Default.aspx。

          CreateImg.aspx页面使用的各个函数如下:

          string getRandomValidate(int len)       得到随机长度为len的字符串

          drawLine(Graphics gfc,Bitmap img)      在图片中画底线

          drawPoint(Bitmap img)                    在图片中画杂点(移动画的杂点挺好不错)

         getImageValidate(string strValue)     使用getRandomValidate函数返回的字符串生成图片

         其具体实现代码如下所示:

using System.Drawing;
using System.IO;

public partial class createImg : System.Web.UI.Page
{
    Random ran = new Random();
      protected void Page_Load(object sender, EventArgs e)
      {
          string str = getRandomValidate(4);
        Session["check"] = str; //这一步是为了将验证码写入Session,进行验证,不能缺省,也可一使用cookie
          getImageValidate(str);
      }
      //得到随机字符串,长度自己定义
      private string getRandomValidate(int len)
      {
          int num;
          int tem;
          string rtuStr = "";
          for (int i = 0; i < len; i++)
          {
              num = ran.Next();
              /*
               * 这里可以选择生成字符和数字组合的验证码
               */
              tem = num % 10 + '0';//生成数字
              //tem = num % 26 + 'A';//生成字符
              rtuStr += Convert.ToChar(tem).ToString();
          }
          return rtuStr;
      }
      //生成图像
      private void getImageValidate(string strValue)
      {
          //string str = "OO00"; //前两个为字母O,后两个为数字0
          int width = Convert.ToInt32(strValue.Length * 12);    //计算图像宽度
          Bitmap img = new Bitmap(width, 23);
          Graphics gfc = Graphics.FromImage(img);           //产生Graphics对象,进行画图
          gfc.Clear(Color.White);
          drawLine(gfc, img);
          //写验证码,需要定义Font
          Font font = new Font("arial", 12, FontStyle.Bold);
          System.Drawing.Drawing2D.LinearGradientBrush brush =
              new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, img.Width, img.Height), Color.DarkOrchid, Color.Blue, 1.5f, true);
          gfc.DrawString(strValue, font, brush, 3, 2);
          drawPoint(img);
          gfc.DrawRectangle(new Pen(Color.DarkBlue), 0, 0, img.Width - 1, img.Height - 1);
          //将图像添加到页面
          MemoryStream ms = new MemoryStream();
          img.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
          //更改Http头
          Response.ClearContent();
          Response.ContentType = "image/gif";
          Response.BinaryWrite(ms.ToArray());
          //Dispose
          gfc.Dispose();
          img.Dispose();
          Response.End();
      }
      private void drawLine(Graphics gfc,Bitmap img)
      {
          //选择画10条线,也可以增加,也可以不要线,只要随机杂点即可
          for (int i = 0; i < 10; i++)
          {
              int x1 = ran.Next(img.Width);
              int y1 = ran.Next(img.Height);
              int x2 = ran.Next(img.Width);
              int y2 = ran.Next(img.Height);
              gfc.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);      //注意画笔一定要浅颜色,否则验证码看不清楚
          }
      }
      private void drawPoint(Bitmap img)
      {
          /*
          //选择画100个点,可以根据实际情况改变
          for (int i = 0; i < 100; i++)
          {
              int x = ran.Next(img.Width);
              int y = ran.Next(img.Height);
              img.SetPixel(x,y,Color.FromArgb(ran.Next()));//杂点颜色随机
          }
           */
          int col = ran.Next();//在一次的图片中杂店颜色相同
          for (int i = 0; i < 100; i++)
          {
              int x = ran.Next(img.Width);
              int y = ran.Next(img.Height);
              img.SetPixel(x, y, Color.FromArgb(col));
          }
      }
}

          如何使用:

          新建一个页面,至少需要一个文本框、image控件和一个Button控件。需要注意的是要将image控件的imageUrl指定为createImg.aspx,如下所示

        <asp:Image ID="Image1" runat="server" ImageUrl="~/createImg.aspx" />

        其测试就很简单了,就像平时使用Session一样,饿,还记得createImg页面中有一个Session["check"]吗?该页面已经注册了一个会话,那么在Default页面中只需简单的比较以下就可以了。

        protected void Page_Load(object sender, EventArgs e)
      {
          if (Session["check"] == null)
              message.Text = "sorry,the image is wrong!";
      }
      protected void checkButton_Click(object sender, EventArgs e)
      {
          if (check.Text.ToString() == Session["check"].ToString())
              message.Text = "Yes,you pass it";
          else
              message.Text = "I'm sorry!try again...";
      }

         测试效果如下图所示:

      


最后结合自己的测试,补充如下:
要想实现刷新验证码而不刷新整个页面,需要在文件中加入:

<a href="javascript:ChangeImage();"><span style="color: #0000ff">看不清</span></a>。

然后在<head>里加入如下js代码(当然加在js文件里更好):

function ChangeImage()
        {
            document.getElementById("Image1").src = document.getElementById("Image1").src+'?';
        }

测试效果如下图所示:

 

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值