.net一般处理程序ashx生成验证码(原创+转载)

//第一种

using System;
using System.Collections.Generic;
using System.Web;
using System.Drawing;
using System.Drawing.Imaging;
using System.Web.SessionState;

namespace sizhengwang.BLL
{
    /// <summary>
    /// GetValImage 的摘要说明
    /// </summary>
    public class GetValImage : IHttpHandler, IRequiresSessionState
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "image/jpeg";
            using (Bitmap bitmap = new Bitmap(80, 20))//创建图片
            {
                using (Graphics gr = Graphics.FromImage(bitmap))//创建图片的画布
                {
                    Random rand = new Random();
                    string code = yzm(4);
                    gr.Clear(Color.White);
                    gr.DrawString(" " + code, new Font("宋体", 14), Brushes.Blue, new PointF(0, 0));

                    bitmap.Save(context.Response.OutputStream, ImageFormat.Jpeg); //返回一个jpeg图片对象
                    HttpContext.Current.Session["code"] = code.ToLower(); //保存到session
                }
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
        public static string yzm(int len) //生成验证码
        {
            string str = "0,1,2,3,4,5,6,7,8,9,";
            str += "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,";
            str += "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";
            string[] s = str.Split(new char[] { ',' });
            string strnum = "";
            int tag = -1;
            Random rnd = new Random();
           
            for (int i = 1; i <= len; i++)
            {
                if (tag == -1)
                {
                    rnd = new Random(i * tag * unchecked((int)DateTime.Now.Ticks));
                }
                int rndnum = rnd.Next(61);
                //if (tag != -1 && tag == rndnum)
                //{
                //    return yzm(1);
                //}
                tag = rndnum;
                strnum += s[rndnum];
            }
            return strnum;
        }
    }
   
}

//第二种(转载)

<%@ WebHandler Language="C#" Class="ValidateCode" %>

using System;
using System.Web;
using System.Drawing;
using System.Web.SessionState;

public class ValidateCode : IHttpHandler, IRequiresSessionState
{
    HttpContext context;
    
    //在此文件被访问时自动调用 相当于页面的PageLoad事件
    public void ProcessRequest (HttpContext context1) {
        this.context = context1;
        CreateCheckCodeImage(GenerateCheckCode());
    }

    #region 生成随机字符串
    /// <summary>
    /// 生成随机字符串
    /// </summary>
    /// <returns></returns>
    private string GenerateCheckCode()
    {
        int number;
        char code;
        string checkCode = String.Empty;

        System.Random random = new Random();

        for (int i = 0; i < 5; i++)
        {
            number = random.Next();

            if (number % 2 == 0)
                code = (char)('0' + (char)(number % 10));
            else
                code = (char)('0' + (char)(number % 10));
            //code = (char)('A' + (char)(number % 26));

            checkCode += code.ToString();
        }

        //Response.Cookies.Add(new HttpCookie("CheckCode", checkCode));
        //当生成好随机字符串后,将它保存在Session
        context.Session["vCode"] = checkCode;//.Add("vCode", checkCode);
        return checkCode;
    }
    #endregion

    /// <summary>
    /// 根据字符串生成图片
    /// </summary>
    /// <param name="checkCode">字符串</param>
    private void CreateCheckCodeImage(string checkCode)
    {
        if (checkCode == null || checkCode.Trim() == String.Empty)
            return;
        System.Drawing.Bitmap image = new System.Drawing.Bitmap((int)Math.Ceiling((checkCode.Length * 12.5)), 22);
        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 System.Drawing.Font("Arial", 12, (System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic));
            System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2f, true);
            g.DrawString(checkCode, font, brush, 2, 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);

            //准备缓存流
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            //将图片流存入缓存流
            image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
            //清空相应对象内容
            context.Response.ClearContent();
            //设置相应对象内容格式为图片
            context.Response.ContentType = "image/Gif";
            //将缓存流中的图片流返回客户端
            context.Response.BinaryWrite(ms.ToArray());
        }
        finally
        {
            g.Dispose();//销毁画板
            image.Dispose();//销毁图片
        }
    }
   
    public bool IsReusable {
        get {
            return false;
        }
    }

}

时间: 2024-12-28 11:49:32

.net一般处理程序ashx生成验证码(原创+转载)的相关文章

.net ashx 生成验证码ProcessRequest执行两次的问题

问题描述 悬赏园豆:30[待解决问题]浏览:1次我直接打开这个链接http://localhost:23011/Login/GetCheckCode.ashx?t=ce7052c1a25f4e1a99525d8c80957180通过ashx生成验证码,image.Save(ms,System.Drawing.Imaging.ImageFormat.Jpeg);context.Response.ClearContent();context.Response.ContentType="image/j

使用ashx文件生成验证码图片

 在vs2005中可以直接创建.ashx文件,其项目叫做一般处理程序,.ashx文件一般用来处理只有返回,二一般不回传的数据,比如动态生成图片,或者文字,以下为清清月儿博客上转载的一个用ashx动态生成验证码图片的代码. //绘制验证码图片ValidateImageHandler.ashx 1 <%@ WebHandler Language="C#" Class="ValidateImageHandler" %> 2  3 using System; 4

【转】C#生成验证码

使用C#生成验证码图片,然后在网页中直接使用,很方便的用法. using System; using System.Drawing; using System.Drawing.Imaging; using System.Web.UI; using System.Drawing.Drawing2D; using System.IO; /// <summary> /// 生成验证码的类 /// </summary> public class ValidateCode { public

asp.net简单生成验证码的方法_实用技巧

本文实例讲述了asp.net简单生成验证码的方法.分享给大家供大家参考,具体如下: 1.新建一个一般处理程序 namespace WebApplication1 { /// <summary> /// $codebehindclassname$ 的摘要说明 /// </summary> [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfil

php生成验证码

本站原创转载请注明来处 <?php session_start(); header("content-type:image/png");设置生成图片的格式这里为png $width=40;//宽度 $height=25;//高度 $color="#ffffff";//色彩 $num=rand(1000,9999);//生成随机数4位 $_SESSION['ver']=$num;保存到session以前验证 $img=imagecreate($width,$he

ASP程序无组件生成验证码

程序|无组件|验证码 一.无组件生成验证码-GIF格式 <%Option Explicit ' 显示声明 Class Com_GifCode_Class'''''''''''''''''''''''''''''''''''''''''''''' Author: Layen support@ssaw.net 84815733(QQ)' Thanks: Laomi, Laomiao, NetRube' 2006-01-02'''''''''''''''''''''''''''''''''''''''

Asp.Net生成验证码

asp.net|验证码      经常在论坛里看到有问怎么实现验证码的帖子,其实关于验证码的文章在csdn,dev-club等网站上都有很多,但是很多文章只讲诉了如何输出一个随机生成数字或字符的图象,当然了,这个是验证码的核心了,但是对很多asp.net的初学者来说,怎么使用它生成的图象又成了一个问题(论坛有不少问这个的),这也是我写本文的一个原因.    言归正传,关于验证码的原理,我就不多说了,大家可以参见其他文章,文末附有完整的实例代码,里面有详细的注释,你可以跳过解说文字,直接使用   

ASP生成验证码详细教程

总共有三个文件.讲解如何通过ASP生成验证码.Asp文件:Code.Asp 数据文件:body.Fix , Head.Fix  用法:<img src="code.asp"> <%Option ExplicitResponse.buffer=trueNumCodeFunction NumCode()    Response.Expires = -1    Response.AddHeader "Pragma","no-cache"

ASP.NET中如何动态生成验证码

现在不少网站中都使用了验证码的技术,实现方式也是多种多样,这里主要介绍ASP.NET中可以采用的一种动态生成验证码的方法,可能并不十分完美,但实现难度是属于较低的. 该方法是利用了普通的动态图片生成技术,但比较特别的一点是图片的生成是在一个Page类型的子类的Page_Load方法中执行的.所以Response的ContentType为image/Gif,而非text/html. GraphicalText.aspx.cs代码: using System; using System.Drawin