生成验证码的例子

<%@ WebHandler Language="C#" class="Handler" %>

using System;
using System.Web;

public class Handler : IHttpHandler,System.Web.SessionState.IRequiresSessionState
{

    //private static System.Random random = new Random();
   
    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "image/jpeg";

        //文件的虚拟路径
        //string path = "~/app_data/background.jpg";
        //string filepath = context.Server.MapPath(path);

        //新创建一个位图对象
        System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(100,80);
       
        //通过随机数生成
        //string message = random.Next(10000, 100000).ToString();
       
       
        //借助Guid生成随机验证码
        System.Guid guid = System.Guid.NewGuid();
        string codestring = guid.ToString().Substring(0, 5);
       
        //使用会话状态
        context.Session["Code"] = codestring;

        //取得用于画图的图形设备
        using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap))
        {
            g.Clear(System.Drawing.Color.DarkOliveGreen);
           
            //矩形
            g.DrawRectangle(
                new System.Drawing.Pen(System.Drawing.Brushes.Black, 3),
                new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height));
           
           
            //对齐
            System.Drawing.StringFormat sf = new System.Drawing.StringFormat();
            sf.Alignment = System.Drawing.StringAlignment.Center;
            sf.LineAlignment = System.Drawing.StringAlignment.Center;

            g.DrawString(
                codestring,
                new System.Drawing.Font("Fixedsys", 18),
                System.Drawing.Brushes.Silver,
                new System.Drawing.RectangleF(0,0,
                bitmap.Width,bitmap.Height),
                sf
            );
           
            
        }
        bitmap.Save(context.Response.OutputStream,
            System.Drawing.Imaging.ImageFormat.Jpeg);
       
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }

}

原文地址:https://www.cnblogs.com/jasonjiang/p/1763746.html