.NET下產生圖片驗證碼

來源:互聯網
上載者:User

後台檔案:

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Drawing;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class Default2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if(!this.IsPostBack)
        {
            this.GenImg(this.GenCode(4));
        }

    }
    //產生隨機字串
    private string GenCode(int num)
    {
        string[] source={"0","1","2","3","4","5","6","7","8","9",
                            "A","B","C","D","E","F","G","H","I","J","K","L","M","N",
                            "O","P","Q","R","S","T","U","V","W","X","Y","Z"};
        string code="";
        Random rd=new Random();
        for(int i=0;i < num;i++)
        {
            code += source[rd.Next(0,source.Length)];
        }
        return code;
    }

    //產生圖片
    private void GenImg(string code)
    {
        Bitmap myPalette = new Bitmap(60, 20);//定義一個畫板

        Graphics gh = Graphics.FromImage(myPalette);//在畫板上定義繪圖的執行個體

        Rectangle rc = new Rectangle(0, 0, 60, 20);//定義一個矩形

        gh.FillRectangle(new SolidBrush(Color.Blue), rc);//填充矩形
        gh.DrawString(code, new Font("宋體", 16), new SolidBrush(Color.White), rc);//在矩形內畫出字串

        myPalette.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);//將圖片顯示出來

        Session["ValidateCode"] = code;//將字串儲存到Session中,以便需要時進行驗證

        gh.Dispose();
        myPalette.Dispose();
    }

}

HTML檔案:

加入一個HTML控制項Image即可
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>

<img src="Default2.aspx" />

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.