using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.IO;
 
/// <summary>
/// 生成验证码的类
/// </summary>
public class ValidateCode
{
    public ValidateCode()
    {
    }
    /// <summary>
    /// 验证码的最大长度
    /// </summary>
    public int MaxLength
    {
        get { return 10; }
    }
    /// <summary>
    /// 验证码的最小长度
    /// </summary>
    public int MinLength
    {
        get { return 1; }
    }
    /// <summary>
    /// 生成验证码
    /// </summary>
    /// <param name="length">指定验证码的长度</param>
    /// <returns></returns>
    public string CreateValidateCode(int length)
    {
        if (length < 1)
        {
            length = 1;
        }
        if (length > 10)
        {
            length = 10;
        }
        string[] sourceCode = new string[] { "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" };
        Random r = new Random(unchecked((int)DateTime.Now.Ticks));
        string codes = "";
        for (int i = 0; i < length; i++)
        {
            int l = r.Next(0, 35);
            codes += sourceCode[l];
        }
        return codes;
    }
 
    /// <summary>
    /// 创建验证码的图片
    /// </summary>
    /// <param name="containsPage">要输出到的page对象</param>
    /// <param name="validateNum">验证码</param>
    public byte[] CreateValidateGraphic(string validateCode)
    {
        Bitmap image = new Bitmap((int)Math.Ceiling(validateCode.Length * 15.0), 24);
        Graphics g = Graphics.FromImage(image);
        try
        {
            //生成随机生成器
            Random random = new Random();
            //清空图片背景色
            g.Clear(Color.White);
            //画图片的干扰线
            for (int i = 0; i < 25; i++)
            {
                int x1 = random.Next(image.Width);
                int x2 = random.Next(image.Width);
                int y1 = random.Next(image.Height);
                int y2 = random.Next(image.Height);
                g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
            }
            Font font = new Font("Arial", 12, (FontStyle.Bold | FontStyle.Italic));
            LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height),
             Color.Blue, Color.DarkRed, 1.2f, true);
            g.DrawString(validateCode, font, brush, 3, 2);
            //画图片的前景干扰点
            for (int i = 0; i < 100; i++)
            {
                int x = random.Next(image.Width);
                int y = random.Next(image.Height);
                image.SetPixel(x, y, Color.FromArgb(random.Next()));
            }
            //画图片的边框线
            g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);
            //保存图片数据
            MemoryStream stream = new MemoryStream();
            image.Save(stream, ImageFormat.Jpeg);
            //输出图片流
            return stream.ToArray();
        }
        finally
        {
            g.Dispose();
            image.Dispose();
        }
    }
    /// <summary>
    /// 得到验证码图片的长度
    /// </summary>
    /// <param name="validateNumLength">验证码的长度</param>
    /// <returns></returns>
    public static int GetImageWidth(int validateNumLength)
    {
        return (int)(validateNumLength * 13.0);
    }
    /// <summary>
    /// 得到验证码的高度
    /// </summary>
    /// <returns></returns>
    public static double GetImageHeight()
    {
        return 22.5;
    }
}

====================ashx================

  public class ashxGetCode : IHttpHandler
    {
 
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            ValidateCode vc = new ValidateCode();
            string code =  vc.CreateValidateCode(4);
            byte[] result =  vc.CreateValidateGraphic(code);
            context.Response.BinaryWrite(result);
        }
 
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }



=============mvc========

public ActionResult GetValidateCode()
{
ValidateCode vCode = new ValidateCode();
string code = vCode.CreateValidateCode(5); 
Session["ValidateCode"] = code; 
byte[] bytes = vCode.CreateValidateGraphic(code); 
return File(bytes, @"image/jpeg");  
}

ashx与验证码的更多相关文章

  1. asp.net中ashx生成验证码代码放在Linux(centos)主机上访问时无法显示问题

    最近有个项目加入了验证码功能,就从自己博客以前的代码中找到直接使用,直接访问验证码页面报错如下: 源代码:asp.net中使用一般处理程序生成验证码 Application Exception Sys ...

  2. 在ashx文件中制作验证码(使用session要继承IRequiresSessionState)

    必须继承System.Web.SessionState.IRequiresSessionState接口,才能实现Session读写! System.Web.SessionState的一些接口 IRea ...

  3. ajax原理,验证码生成原理

    什么是ajax AJAX:”Asynchronous JavaScript and XML” 中文意思:异步JavaScript和XML 指一种创建交互式网页应用的网页开发技术.   不是指一种单一的 ...

  4. C# WinForm 上传图片,文件到服务器的方法Uploader.ashx

    网上有很多方案,起初用时,因为对asp.net不太了解,觉得FTP实现不错,可是后来发现,如果机器在域控下,就会有问题. 一年过去了,asp.net也熟悉了,知道ajax没事应该用ashx,验证码也用 ...

  5. 用Session实现验证码

    新建一个 ashx 一般处理程序 如: YZM.ashx继承接口 IRequiresSessionState //在一般处理程序里面继承 HttpContext context 为请求上下文,包含此次 ...

  6. GDI+ 实例:绘制验证码

    一.概述 一般处理程序 ashx :它没有服务器控件,用response输出什么就是什么. 生成验证码原理:产生随机字符,并将字符生成为图片,同时储存到Session里去,然后验证用户输入的内容是否与 ...

  7. python爬虫模拟登录的图片验证码处理和会话维持

    目标网站:古诗文网 登录界面显示: 打开控制台工具,输入账号密码,在ALL栏目中进行抓包 数据如下: 登录请求的url和请求方式 登录所需参数 参数分析: __VIEWSTATE和__VIEWSTAT ...

  8. XX管理系统案例

    一.登录界面建立登录文件夹Login,在此目录下面建立如下文件:Index.htm:登录页面ValidateCode.cs:生成验证码ProcessVerification.ashx:处理验证码Com ...

  9. 【Xamarin挖墙脚系列:Mono项目的图标为啥叫Mono】

    因为发起人大Boss :Miguel de lcaza 是西班牙人,喜欢猴子.................就跟Hadoop的创始人的闺女喜欢大象一样...................... 历 ...

随机推荐

  1. MySQL同主机不同数据库的复制命令

    MySQL同主机不同数据库的复制命令:注意运行在Terminal中,不运行在MySQL命令行中. 1 mysqldump Portal_DEV -u root -ppassword1$ --add-d ...

  2. getComputedStyle和currentStyle

    /*alert(div.style.width)*/ //null function getstyle(obj,name){ if(obj.currentStyle) { return obj.cur ...

  3. Android手机播放电脑视频文件-屌丝必备

    今天早上一到办公室,照常打开博客园看文章,看到有一片文章是用  http://www.cnblogs.com/wdfrog/p/3738180.html 看到这哥们实现的方法好复杂,又是配置电脑端,又 ...

  4. HOWTO: Be more productive

    ---by   Aaron Swartz HOWTO: Be more productive “With all the time you spend watching TV,” he tells m ...

  5. Smarty模板引擎技术二

    Smarty模板引擎技术 内建函数 include_php内建函数 作用:载入一个php文件,将载入的文件的内容赋值给一个变量   注意:该内建函数只能在2.0中使用,如果使用的话,必须得实例化Sma ...

  6. Remote Desktop Organizer远程桌面管理软件的基本使用和介绍

    <Remote Desktop Organizer>是一款用于远程桌面管理的软件.软件支持windows平台运行. Remote Desktop Organizer 是一款 Windows ...

  7. undrop for innodb c_parser 不完美之处

    今天发现c_parser导出数据是会丢掉某些行,给过调试发现是他处理utf8编码时计算有误,目前还没有发现自动解决总是的方法,只会手动改代码来解决. 下一步计划把c_parser移植到windows下 ...

  8. 集成产品开发-IPD简介

    内训IPD流程,听完后,觉的流程的力量很强大,可以高效的团队几千上万人的研发团队,来正确地为同一个目标前进.因为讲解者是从华为出来的,所以,相关的案例分析以及理解,都是以华为研发为模板来讲解的.这没错 ...

  9. Java权限讲解

    Java访问权限就如同类和对象一样,在Java程序中随处可见. Java的访问权限,根据权限范围从大到小为:public > protected > package > privat ...

  10. OpenCV和Matplotlib色彩空间模式不一致的问题

    当用OpenCV读取彩色图像时,OpenCV是以(BGR)的顺序存储图像数据的,而Matplotlib是以(RGB)的顺序显示图像的. 可以用下面的程序来证明这一点 import cv2 import ...