Webfrom --圖片驗證碼

(一) 添加一個通常處理程序,dom

<%@ WebHandler Language="C#" Class="show" %>

using System;
using System.Web;
using System.Drawing;//引用
using System.Web.SessionState;//IRequiresSessionState的命名空間

public class show : IHttpHandler, IRequiresSessionState
{

    public void ProcessRequest(HttpContext context) { context.Response.ContentType = "image/jpeg";//要輸出的類型 Bitmap img = new Bitmap(50, 20);//造空白圖 Graphics gr = Graphics.FromImage(img);//往哪一個圖上去繪製 Font font = new Font("宋體", 12, FontStyle.Bold);//設置字體 SolidBrush brush = new SolidBrush(Color.White);//設置刷子 gr.FillRectangle(brush, 0, 0, 50, 20);//刷子繪製的形狀 brush.Color = Color.Red;//顏色

        string s = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
        string str = "";
        Random rand = new Random();//初始化隨機數
        for (int i = 0; i < 4; i++)
        {
            int start = rand.Next(62); //生成一個隨機的起始位置
            str += s.Substring(start, 1).ToString();
        }
        //須要繼承接口
        context.Session["yanzheng"] = str;
        gr.DrawString(str, font, brush, 0, 0);//繪製完了圖片了
        //將圖片保存,經過response響應流保存
        img.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

}

(二)製做一個主頁面 Default字體

添加一個imagebutton , textbox ,buttonui

不要忘記在imageUrl中添加寫的圖片的方法。spa

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

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void Button1_Click(object sender, EventArgs e) { string txtyanzheng = TextBox1.Text; if (string.IsNullOrWhiteSpace(txtyanzheng)) { } else { string yanzheng = Session["yanzheng"].ToString(); //用Session傳值接收過來 if (txtyanzheng == yanzheng) { Response.Write("<script>alert('註冊成功')</script>"); } else { Response.Write("<script>alert('驗證碼不正確')</script>"); } }
    }
    
 
}

效果圖:code

相關文章
相關標籤/搜索