Webform 验证码制作

实现功能:点击图片刷新验证码,输入进行验证,并且提示客户是否成功

 

验证码单独放在一个页面中:

后台代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;

public partial class Yzm : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Random r = new Random();
        
        //定义一组颜色,
        List<Color> clist = new List<Color>();
        clist.Add(Color.Red);
        clist.Add(Color.Sienna);
        clist.Add(Color.Thistle);
        clist.Add(Color.Sienna);
        clist.Add(Color.PeachPuff);
        clist.Add(Color.Pink);
        clist.Add(Color.Moccasin);
        clist.Add(Color.SeaShell);


        //验证码需要的文字
        string all = "ABCDEFGHLGKMNOPQISTUVWXYZabcdefghlgkmnopqistuvw0123456789";
        string s = null;
        for (int i = 0; i < 4;i++ ) 
        {
            s += all.Substring(r.Next(0,all.Length),1);
        }

        Session["YZM"] = s;

        //放验证码的图片
        Bitmap img = new Bitmap(60,40);
        //绘制背景图片
        Graphics g1 = Graphics.FromImage(img);
            //背景颜色需要随机生成
        Brush b1 = new SolidBrush(clist[r.Next(0,clist.Count)]);
        g1.FillRectangle(b1, 0, 0, 60, 40);


        //绘制验证码
        Graphics g = Graphics.FromImage(img);
        //绘制的字体样式
        Font f = new Font("微软雅黑",15);
        //绘制随机数的颜色
        Brush b = new SolidBrush(clist[r.Next(0, clist.Count)]);
        //绘制的坐标点
        Point p = new Point(0,0);
        g.DrawString(s, f, b, p);


        //绘制线条,对验证码进行遮罩
        for(int i=0;i<r.Next(4,8);i++)
        {
            Graphics g3 = Graphics.FromImage(img);
            Pen p3 = new Pen(new SolidBrush(clist[r.Next(0, clist.Count)]),r.Next(2,5));
            g.DrawLine(p3, r.Next(0, 60), r.Next(0, 40), r.Next(0, 60), r.Next(0, 40));
        }   

        img.Save(Response.OutputStream,System.Drawing.Imaging.ImageFormat.Png);



    }
}

引用验证码的页面:

页面代码:

  布局代码:

<div>
      <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <img  id="YZM" src="Yzm.aspx"/><br />
        <asp:Button ID="Button1" runat="server" Text="验证" /><br />
        <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
    </div>

Js代码:

 var a = 0;
    document.getElementById('YZM').onclick = function () {
        this.src = "Yzm.aspx?a=" + a;
        a++;
    }

后台代码:

protected void Page_Load(object sender, EventArgs e)
    {
        Button1.Click += Button1_Click;
    }

    void Button1_Click(object sender, EventArgs e)
    {
        //将生成的验证码和客户输入的验证码进行转换为大写
        if (Session["YZM"].ToString().ToUpper() == TextBox1.Text.ToUpper())
        {
            Label1.Text = "验证成功";
        }
        else { Label1.Text = "验证失败"; }
    }

 

原文地址:https://www.cnblogs.com/qingnianxu/p/6973498.html