using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.Drawing.Drawing2D;
using System.Drawing;
using System.IO;
using System.Drawing.Imaging;
 
public partial class ValidateCode : System.Web.UI.Page
{
    private string code;
    private const int ImageHeigth = 22;             //验证码图片的高度
    private const double ImageLengthBase = 12.5;    //验证码图片中每个字符的宽度
    private const int ImageLineNumber = 25;         //噪音线的数量
    private const int ImagePointNumber = 100;       //噪点的数量
    private int length;
    public static string VALIDATECODEKEY;       //此处用来保存验证码到Session的Key的名称
 
    //静态构造函数初始化验证码在Session中的Key名称
    static ValidateCode()
    {
        VALIDATECODEKEY = "VALIDATECODEKEY";
    }
 
    //设置验证码的长度和内容
    public ValidateCode()
    {
        this.length = 4;
        this.code = string.Empty;
    }
 
    ///
    /// 产生随机的验证码并加入Session
    ///
    /// 验证码长度
    ///
    public string CreateCode(int length)
    {
        if (length <= 0)
        {
            return string.Empty;
        }
        Random random = new Random();
        StringBuilder builder = new StringBuilder();
        //产生随机的验证码并拼接起来
        for (int i = 0; i < length; i++)
        {
            builder.Append(random.Next(0, 10));
        }
        this.code = builder.ToString();
        this.Session[VALIDATECODEKEY] = this.code;
        return this.code;
    }
 
    ///
    /// 根据长度产生验证码
    /// 并将验证码画成图片
    ///
    /// 验证码长度
    public void CreateValidateImage(int length)
    {
        this.code = this.CreateCode(length);
        this.CreateValidateImage(this.code);
    }
    ///
    /// 根据产生的验证码生成图片
    ///
    /// 验证码
    public void CreateValidateImage(string code)
    {
        if (!string.IsNullOrEmpty(code))
        {
            this.Session[VALIDATECODEKEY] = code;
            //初始化位图Bitmap对象,指定图片对象的大小(宽,高)
            Bitmap image = new Bitmap((int)Math.Ceiling((double)(code.Length * ImageLengthBase)), ImageHeigth);
            //初始化一块画布
            Graphics graphics = Graphics.FromImage(image);
            Random random = new Random();
            try
            {
                int num5;
                graphics.Clear(Color.White);
                //绘制噪音线
                for (num5 = 0; num5 < ImageLineNumber; num5++)
                {
                    int num = random.Next(image.Width);
                    int num3 = random.Next(image.Height);
                    int num2 = random.Next(image.Width);
                    int num4 = random.Next(image.Height);
                    graphics.DrawLine(new Pen(Color.Silver), num, num3, num2, num4);
                }
                //验证码字体样式
                Font font = new Font("Tahoma", 12, FontStyle.Italic | FontStyle.Bold);
                LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2f, true);
                //绘制验证码到画布
                graphics.DrawString(code, font, brush, (float)2, (float)2);
                //绘制噪点
                for (num5 = 0; num5 < ImagePointNumber; num5++)
                {
                    int x = random.Next(image.Width);
                    int y = random.Next(image.Height);
                    image.SetPixel(x, y, Color.FromArgb(random.Next()));
                }
                graphics.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);
                MemoryStream stream = new MemoryStream();
                //保存图片
                image.Save(stream, ImageFormat.Gif);
                base.Response.ClearContent();
                base.Response.ContentType = "image/Gif";
                base.Response.BinaryWrite(stream.ToArray());
            }
            finally
            {
                graphics.Dispose();
                image.Dispose();
            }
        }
    }
    protected override void OnLoad(EventArgs e)
    {
        this.CreateValidateImage(this.length);
    }
 
    // Properties
    public string Code
    {
        get
        {
            return this.Code;
        }
    }
    public int Length
    {
        get
        {
            return this.length;
        }
        set
        {
            this.length = value;
        }
    }
}

再次申明非本人原创。可以到网上下载ASPNETAJAXWeb.ValidateCode.dll直接使用

C#产生随机验证码的代码的更多相关文章

  1. Python生成随机验证码,大乐透号码

    实例笔记之生成随机号码 扩展知识 - yield(生成器) 随机生成验证码 示例代码: import random # 导入标准模块中的random if __name__ == '__main__' ...

  2. 【代码实现】PHP生成各种随机验证码

    原文地址:http://www.phpthinking.com/archives/531 验证码在WEB应用中很重要,通经常使用来防止用户恶意提交表单,如恶意注冊和登录.论坛恶意灌水等.本文将通过实例 ...

  3. 随机验证码生成(python实现)

    需求:生成随机不重复验证码. 代码: #!/usr/bin/env python # encoding: utf-8 """ @author: 侠之大者kamil @fi ...

  4. php学习笔记:利用gd库生成图片,并实现随机验证码

    说明:一些基本的代码我都进行了注释,这里实现的验证码位数.需要用的字符串都可以再设置.有我的注释,大家应该很容易能看得懂. 基本思路: 1.用mt_rand()随机生成数字确定需要获取的字符串,对字符 ...

  5. python_way,day4 内置函数(callable,chr,随机验证码,ord),装饰器

    python_way,day4 1.内置函数 - 下 制作一个随机验证码 2.装饰器 1.内置函数 - 下 callable() #对象能否被调用 chr() #10进制数字对应的ascii码表中的内 ...

  6. python-Day5-深入正则表达式--冒泡排序-时间复杂度 --常用模块学习:自定义模块--random模块:随机验证码--time & datetime模块

    正则表达式   语法:             mport re #导入模块名 p = re.compile("^[0-9]") #生成要匹配的正则对象 , ^代表从开头匹配,[0 ...

  7. python之使用PIL模块制作随机验证码

    制作随机验证码,需要如下知识点: 1.随机验证码的制作(这里用的是random模块随机产生字符) 2.图片的制作 3.随机直线干扰项 4.其他随机干扰项 代码如下: from PIL import I ...

  8. Python使用PIL模块生成随机验证码

    PIL模块的安装 pip3 install pillow 生成随机验证码图片 import random from PIL import Image, ImageDraw, ImageFont fro ...

  9. C#生成随机验证码例子

    C#生成随机验证码例子: 前端: <tr> <td width=" align="center" valign="top"> ...

随机推荐

  1. python 匿名函数lambda使用

    lambda函数语法格式: lambda函数 后面参数可以有一个或多个,冒号后面是python表达式: lambda 参数1,参数2,参数3...:表达式 # 一个参数情况: a = lambda x ...

  2. 【3】Zookeeper中的角色

    一.Zookeeper角色的分类 领导者(leader) Leader服务器为客户端提供读服务和写服务. 学习者(learner) 跟随者(follower) Follower服务器为客户端提供读服务 ...

  3. contextlib:上下文管理器工具

    介绍 contextlib模块包含的工具可以用于处理上下文管理器和with语句 上下文管理器API ''' 上下文管理器(context manager)负责管理一个代码块中的资源,会在进入代码块时创 ...

  4. Java 通过Math.random() 生成6位随机数

    public static void main(String[] args) { String sjs=""; for (int i = 0; i < 6; i++) { i ...

  5. C++——函数

    C++基础函数 (一)函数的参数传递 在没有调用函数之前,函数的形参并没有占据实际的空间. 1.值传递 传入的仅仅只是一个值--就是把实参的值赋给形参.形参自己会在内存中开辟一个空间! 2.传引用 这 ...

  6. IO框架:asyncio 下篇

    动态添加协程 在实战之前,我们要先了解下在asyncio中如何将协程态添加到事件循环中的.这是前提. 如何实现呢,有两种方法: 主线程是同步的 import time import asyncio f ...

  7. linux命令集锦 基于centos7---优化linux的命令

    sed -i ‘s###g’ /etc/selinux/config  3个# 用于更改selinux配置文件:sed -i 's#SELINUX=enforcing#SELINUX=disabled ...

  8. Hive中运行HQL语句错误

    错误:org.apache.hadoop.yarn.exceptions.InvalidAuxServiceException( 或者为FAILED: Execution Error, return ...

  9. ZOJ - 3715贪心

    ZOJ - 3715KindergartenElection 题目大意:幼儿园里正在举办班长选举,除1号小朋友外每个人都会投他最好的朋友,但1号小朋友可以贿赂别人(小伙子有丶想法),被贿赂的小朋友就会 ...

  10. 「美团 CodeM 初赛 Round A」试题泛做

    最长树链 树形DP.我们发现gcd是多少其实并不重要,只要不是1就好了,此外只要有一个公共的质数就好了.计f[i][j]表示i子树内含有j因子的最长链是多少.因为一个数的不同的质因子个数是log级别的 ...