asp.net可刷新的验证码

//ValidCode.aspx.cs文件

using System;
using System.Data;
using System.Configuration;
using System.Collections;
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;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.Drawing;

public partial class ValidCode : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Random rd = new Random(); //创建随机数对象      

        //以下4行,产生由6个字母和数字组成的一个字符串
        string str = "ABCDEFGHIJKLMNOPQRSTURWXYZ0123456789"; //0-35
        string myValid = "";
        for (int i = 0; i < 6; i++)
        {
            myValid = myValid + str.Substring(rd.Next(35), 1);
        }
        //验证码值存放到Session中用来比较
        Session["Valid"] = myValid;

        //以下三句,通过随机找一个现有图象产生一个画布Bitmap
        string bgFilePath = Server.MapPath(".//Images//ValidBg//bg" + new Random().Next(5) + ".jpg");//随机找个图象
        System.Drawing.Image imgObj = System.Drawing.Image.FromFile(bgFilePath);
        Bitmap newBitmap = new Bitmap(imgObj, 91, 25);//建立位图对象

        Graphics g = Graphics.FromImage(newBitmap);//根据上面创建的位图对象创建绘图面
        SolidBrush brush = new SolidBrush(Color.Black);//设置画笔颜色

        //定义一个含10种字体的数组
        String[] fontFamily ={ "Arial", "Verdana", "Comic Sans MS", "Impact", "Haettenschweiler", "Lucida Sans Unicode", "Garamond", "Courier New", "Book Antiqua", "Arial Narrow" };

        //通过循环,绘制每个字符,
        for (int a = 0; a < myValid.Length; a++)
        {
            Font textFont = new Font(fontFamily[rd.Next(10)], 12, FontStyle.Regular);//字体随机,字号大小30,加粗
            //每次循环绘制一个字符,设置字体格式,画笔颜色,字符相对画布的X坐标,字符相对画布的Y坐标
            g.DrawString(myValid.Substring(a, 1), textFont, brush, 2 + a * 15, 2);
        }

        //保存画的图片到输出流中
        newBitmap.Save(Response.OutputStream, ImageFormat.Gif);
    }
}

 

 

//需要验证码的文件加入

<img id="imgRandom" alt="看不清?点击更换" title="看不清?点击更换" onclick="ShowValidImage()" src="ValidCode.aspx?" />

<script type="text/javascript">

        function ShowValidImage() {
        var numkey = Math.random();
        document.getElementById("imgRandom").src = "ValidCode.aspx?NumKey="+numkey;
    }
</script>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值