.net 验证码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;
using System.Drawing.Imaging;

public partial class Admin_verify : System.Web.UI.Page
{
    private int codelen = 4; //验证码长度
    private int finenes = 85; //图片清晰度
    private int imageHeight = 24;//图片高度
    private int imgWidth = 48; //图片宽度
    private string fontfamily = "微软雅黑"; //字体样式
    private int fontsize = 14; //字体大小
    private int x = 0; //x坐标
    private int y = 0; //y坐标
    
    
    protected void Page_Load(object sender, EventArgs e)
    {
        //验证码

        string validateCode = CreateCodeVerfiy();//生成验证码 
        Bitmap bitmap = new Bitmap(imgWidth, imageHeight);//生成Bitmap图像 
        ImageBig(bitmap); //图像背景 
        DrewValidateCode(bitmap, validateCode);//绘制验证码图像 
        bitmap.Save(Response.OutputStream, ImageFormat.Jpeg);//保存图像,等待输出 


    }
    //验证码数字的生成
    protected string CreateCodeVerfiy() 
    {
        string code = "";
        Random rd = new Random();
        for (int i = 0; i < codelen; i++) 
        {
            int n = rd.Next(10); //随机生成4个数字
            code += n.ToString();
        }
        Session["verify"] = code;
        return code;
    }

    //干扰点生成
    protected void ImageBig(Bitmap bimtmp) 
    {
        Random rd = new Random();
        for (int i = 0; i < bimtmp.Width; i++) 
        {
            for (int j = 0; j < bimtmp.Height; j++) 
            {
                if (rd.Next(90) <= this.finenes) 
                {
                    bimtmp.SetPixel(i, j, Color.LightBlue);
                }
            }
        }
    }

    private void DrewValidateCode(Bitmap bitmap, string validateCode)//绘制验证码图像 
    {
        Graphics g = Graphics.FromImage(bitmap);//获取绘制器对象 
        Font font = new Font(fontfamily, fontsize, FontStyle.Bold);//设置绘制字体 
        g.DrawString(validateCode, font, Brushes.Black, x, y);//绘制验证码图像 
    } 
}

 

posted @ 2016-11-28 15:39  尘梦  阅读(222)  评论(0编辑  收藏  举报