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. 附件上传vue组件封装(一)

    //父页面部分 <attachment @newFileList="newFileList" :operationType="operationType" ...

  2. ath6kl 架构

    转:http://blog.csdn.net/robertsong2004/article/details/38899415 AR600x软件被划分为主机端和目标端软件.主机端软件或驱动程序的代码被提 ...

  3. main特别之处

    //package new_Object; public class Main{ public static void main(String[] args) { System.out.println ...

  4. Go语言基础之Cookie和Session

    Cookie和Session Cookie和Session是Web开发绕不开的一个环节,本文介绍了Cookie和Session的原理及在Go语言中如何操作Cookie. Cookie Cookie的由 ...

  5. 认识并初步应用GitHub

    好好学习,天天向上 一.这是一个简单的开头 GIT的地址 https://github.com/Notexcellent GIT的用户名 Notexcxllent 学号后五位 82405 博客地址 h ...

  6. java线程基础巩固---Daemon线程的创建以及使用场景分析

    daemon线程既守护线程,而在jdk中对于Thread中针对守护线程有专门的API,如下: 而之前在公司项目中就看到过有人使用过Thread中的这个API,但是对于它的使用场景完全不知,所以这次好好 ...

  7. SpringData JPA 在解析实体类字段时驼峰自动添加下划线问题

    参考地址:https://my.oschina.net/javamaster/blog/2246886 SpringData JPA 使用的默认命名策略是: ImprovedNamingStrateg ...

  8. No valid Maven installation found. Either set the home directory in the configuration dialog or set

    原因: IDEA的maven地址设置出错,系统找不到指定的maven路径 解决: setting---->maven修改正确的maven链接地址. 设置你maven 的地址为你的存放路基就好了

  9. Spark RDD初探(一)

    本文概要 本文主要从以下几点阐述RDD,了解RDD 什么是RDD? 两种RDD创建方式 向给spark传递函数Passing Functions to Spark 两种操作之转换Transformat ...

  10. BSGS 扩展大步小步法解决离散对数问题 (BZOJ 3239: Discrete Logging// 2480: Spoj3105 Mod)

    我先转为敬? orz% miskcoo 贴板子 BZOJ 3239: Discrete Logging//2480: Spoj3105 Mod(两道题输入不同,我这里只贴了3239的代码) CODE ...