当前位置 : 主页 > 网页制作 > html >

实践网页图片验证码

来源:互联网 收集:自由互联 发布时间:2021-06-12
摘要:实践网页图片验证码 我们在浏览许多网站时常会看到图片验证码这种东西,例如:BLOG回文、留言板...等等。笔者今天要跟各位介绍如何实践网页图片验证码,下面这种方式是目前最

摘要:实践网页图片验证码


我们在浏览许多网站时常会看到图片验证码这种东西,例如:BLOG回文、留言板...等等。笔者今天要跟各位介绍如何实践网页图片验证码,下面这种方式是目前最常见到的,各位也可自行搭配AJAX来使用。

? 首先建立一个产生验证码的网页,我们先将它命名为ValidateCode.aspx,其产生验证码图片的程序如下:

?? ValidateCode.aspx.cs

???15?protected void Page_Load(object sender, EventArgs e)

???16???? {

???17???? ??? //Validate Code

???18???? ??? string[] Code ={ "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M",

???19???? ??? ??? ??? ??? ??? "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z",

???20???? ??? ??? ??? ??? ??? "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };

???21???? ??? string strRd = string.Empty;

???22

???23???? ??? Random rd = new Random(unchecked((int)DateTime.Now.Ticks));

???24???? ??? Bitmap Bmp = new Bitmap(80, 25);? //建立实例图档并设定大小

???25???? ??? Graphics Gpi = Graphics.FromImage(Bmp);

???26???? ??? Font Font1 = new Font("Verdana", 14, FontStyle.Italic);

???27

???28???? ??? for (int i = 0; i < 5; i++)??? ?? // 随机数产生验证文字

???29???? ??? {

???30???? ??? ??? strRd += Code[rd.Next(35)];

???31???? ??? }

???32

???33???? ??? Pen PenLine = new Pen(Brushes.Red, 1);? //实例化笔刷并设定颜色、大小(画X,Y轴用)

???34???? ??? Gpi.Clear(Color.White);??? //设定背景颜色

???35???? ??? Gpi.DrawLine(PenLine, 0, rd.Next(80), 90, rd.Next(25));

???36???? ??? Gpi.DrawString(strRd, Font1, Brushes.Black, 0, 0);

???37

???38???? ??? for (int i = 0; i <= 25; i++)??? ??? ??? //随机数产生雾点,扰乱机器人辨别

???39???? ??? {

???40???? ??? ??? int RandPixelX = rd.Next(0, 80);

???41???? ??? ??? int RandPixelY = rd.Next(0, 25);

???42???? ??? ??? Bmp.SetPixel(RandPixelX, RandPixelY, Color.Blue);

???43???? ??? }

???44

???45???? ??? Session["ValidateCode"] = strRd;??? ??? //将验证码存入Session以便稍后进行验证

???46???? ??? Bmp.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Gif);

???47???? }

  • 实际运行ValidateCode.aspx将产生下面这张图片

????????????????????? untitled

接着我们来测试图片验证的功能,请在您的Default.aspx加入TextBox控件、Button控件及一张图片(如下图)。

untitled

Default.aspx

??? Validate Code

????ValidateCode:

???

????

?

Default.aspx.cs

??

?? 17???? protected void Button1_Click(object sender, EventArgs e)

???18???? {

???19???? ??? if (TextBox1.Text == (string)Session["ValidateCode"])

???20???? ??? ??? Response.Write("OK");

???21???? ??? else

???22???? ??? ??? Response.Write("ERROR");

???23???? }



  • OK...现在来执行看看Default.aspx

??????? untitled

????????请在验证图片上按下【鼠标右键】->【内容】,我们可以很清楚看到验证图片的来源是ValidateCode.aspx

??????? untitled

??????? 这时候输入正确的验证码就会出现【OK】如果输入错误的验证码就会出现【ERROR

????? untitled?OR untitled

??????? 图片验证码的部分大概就是这样,图片的【字体】、【背景】、【大小】...等等,各位可自行发挥运用。



分享图片分享图片

&amplt;a href=&quothttp://www.facebook.com/sharer.php&quot _cke_saved_href=&quothttp://www.facebook.com/sharer.php&quot type=&quotbutton_count&quot name=&quotfb_share&quot&ampgt;分享&amplt;/a&ampgt;

原文:大专栏  实践网页图片验证码

网友评论