自动生成验证码

来源:互联网 发布:java 类型擦除 编辑:程序博客网 时间:2024/05/22 04:50

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

namespace WebApplication1
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string strCode = GetCode();//通过GetCode()函数获得随机数
            DrawCode(strCode);//通过DrawCode()函数将生成的随机数放入画布中
        }
        //protected string GetCode()//只能生成数字
        //{
        //    string strCode = "";
        //    Random rand = new Random();
        //    int nNum = 0;
        //    for (int nI = 0; nI < 4; nI++)
        //    {
        //        nNum = rand.Next(0, 9);//将随机生成的数字赋给nNum
        //        strCode += nNum.ToString();
        //    }
        //    return strCode;
        //}
        protected string GetCode()
        {
            string str = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
            string strCode = "";
            Random rand = new Random();
            int nNum = 0;
            for (int i = 0; i < 4; i++)
            {
                nNum = rand.Next(35);
                strCode += str.Substring(nNum, 1);
            }
            return strCode;
        }
        protected void DrawCode(string strCode)
        {
            //Session["Code"] = strCode;
            Bitmap bmp = new Bitmap(strCode.Length * 12 + 10, 22);//建立一个Bitmap函数,括号内为图片大小
            Graphics g = Graphics.FromImage(bmp);//从指定的bmp中创建新的绘图面
            g.Clear(Color.White);//清除整个新的绘图面并以指定背景色填充

            //画图片的背景噪音线
            Random random = new Random();
            for (int i = 0; i < 25; i++)
            {
                int x = random.Next(bmp.Width);
                int y = random.Next(bmp.Height);
                g.DrawLine(new Pen(Color.Silver), x, y, x, y);//绘制一条连接由坐标对指定两点的线条
            }
            //画图片的前景噪音点
            for (int i = 0; i < 100; i++)
            {
                int x = random.Next(bmp.Width);
                int y = random.Next(bmp.Height);
                bmp.SetPixel(x, y, Color.FromArgb(random.Next()));//获取bmp中指定像素的颜色
            }
            //画图片的边框线
            g.DrawRectangle(new Pen(Color.Silver), 0, 0, bmp.Width - 1, bmp.Height - 1);//绘制由坐标对、宽度和高度指定的矩形
            g.DrawString(strCode, new Font("宋体", 10), new SolidBrush(Color.Black), 10, 10);//在指定的位子绘制文本字符串
            bmp.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);// 以Jpeg格式保存图片
        }
    }
}