ASP.NET随机生成四位验证码

default.aspx(设计页面)

 

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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>无标题页</title>
</head>
<body>
    <form id="form1" runat="server">
    <div id="DIV1" runat="server">
        &nbsp;</div>
    </form>
</body>
</html>

 

default.aspx.cs(后台代码)

 

using System.Web.UI.HtmlControls;
using System.Drawing.Imaging;
using System.IO;
using System.Drawing;

public partial class image : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        this.GenImg(this.GenCode(4));
        将验证码存储到session中,以便需要时进行验证
        Session["image"] = this.GenCode(6);

    }
    //任意产生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);
        gh.Dispose();        
        myPalette.Dispose();    
    }     
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值