ASP.NET純數字驗證碼

來源:互聯網
上載者:User
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Drawing;
using System.Drawing.Imaging;

public partial class Rnd : System.Web.UI.Page
{
    private int codeLen = 5;//隨機顯示字元個數
    private int fineness = 85;//圖片清晰度
    private int imgWidth = 65;//圖片寬度
    private int imgHeight = 20;//圖片高度
    private string fontFamily = "Comic Sans MS";//字型名稱
    private int fontSize = 12; //字型大小
    private Random random = new Random();
    
    protected void Page_Load(object sender, EventArgs e)
    {
        string validateCode = CreateValidateCode();
        Session["RandomNumber"] = validateCode;
        Bitmap bitmap = new Bitmap(imgWidth, imgHeight);
        DisturbBitmap(bitmap);
        DrawValidateCode(bitmap, validateCode);
        bitmap.Save(Response.OutputStream, ImageFormat.Gif);
    }
    private string CreateValidateCode()//得到隨機數
    {
        string validateCode = "";
        for (int i = 0; i < codeLen; i++)
        {
            int n = random.Next(10);//返回一個小於最大值得隨機數
            validateCode += n.ToString();
        }
        return validateCode;
    }
    private void DisturbBitmap(Bitmap bitmap)//擷取背景圖
    {
        for (int i = 0; i < bitmap.Width; i++)
        {
            for (int j = 0; j < bitmap.Height; j++)
            {
                if (random.Next(90) <= this.fineness)
                {
                    bitmap.SetPixel(i, j, Color.White);//擷取指定位置的像素顏色
                }
            }
        }
    }
    private void DrawValidateCode(Bitmap bitmap, string validateCode)
    {
        Graphics g = Graphics.FromImage(bitmap);
        Font font = new Font(fontFamily, fontSize, FontStyle.Bold);
        g.DrawString(validateCode, font, Brushes.Black, random.Next(-3, 11), random.Next(-4, 1));//在指定地區繪製文本字元
    }
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.