圖片驗證碼

一、建立一個網站,只使用後臺生成驗證碼,並輸出圖片流跟圖片驗證碼的字符javascript

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)
    {
        //1、引用using System.Drawing;類
        //2、準備畫布
        Bitmap img = new Bitmap(60,30);
        //3、往圖片上畫驗證碼
        //一、準備繪製類,至關於鋪好畫布準備繪畫
        Graphics g = Graphics.FromImage(img);
        //二、準備繪畫的內容與工具
        string all = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";//驗證內容
        Random r = new Random();//實例化隨機類
        string aa = "";
        for(int i=0;i<4;i++)
        {
            aa += all.Substring(r.Next(all.Length), 1);//隨機截取字符組成驗證碼
        }
        Session["YZM"] = aa;//驗證的數據用session傳過去
        Font f = new Font("微軟雅黑",16);//字體格式
        SolidBrush b = new SolidBrush(Color.Green);//準備畫刷
        //三、繪製驗證碼
        g.DrawString(aa, f, b, 0, 0);

        //4、輸出驗證碼到頁面上
        img.Save(Response.OutputStream,System.Drawing.Imaging.ImageFormat.Png);//數據流,輸出格式
        
    }
}

二、圖片驗證碼須要驗證的界面html

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

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><asp:Image ID="Image1" runat="server" ImageUrl="~/YZM.aspx" /><br />
        <asp:Button ID="Button1" runat="server" Text="驗證" /><asp:Label ID="Label1" runat="server" Text="" ForeColor="Red"></asp:Label>
    </div>
    </form>
</body>
</html>
<script type="text/javascript">
    //驗證圖片的點擊事件,點擊圖片從新換一張圖片
    var bb = 0;
    document.getElementById("Image1").onclick = function () {
        this.setAttribute("src", "yzm.aspx?aa=" + bb );
        bb++;
    }

</script>

界面後臺java

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

public partial class PMShtml : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Button1.Click += Button1_Click;//驗證按鈕事件
    }

    //驗證按鈕開始
    void Button1_Click(object sender, EventArgs e)
    {
        if (Session["YZM"] != null)
        {
            if (TextBox1.Text == Session["YZM"].ToString())
            {
                Label1.Text = "驗證成功!";
            }
            else
            {
                Label1.Text = "驗證失敗!";
            }
        }
    }
    //驗證按鈕結束
}

相關文章
相關標籤/搜索