简单的验证码控件

不是很漂亮,只是用于研究其原理;

是新建了一个ashx文件(一般处理程序,因为我还在学习中……)

在aspx页中的form表单中添加调用;

 <img src="验证码实例.ashx" alt="" />

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

namespace WebApp
{
    
/// <summary>
    
/// 验证码实例 的摘要说明
    
/// </summary>
    public class 验证码实例 : IHttpHandler, IRequiresSessionState   //在一般处理程序中使用Session要实现该接口,在System.Web.SessionState中;
    {

        
public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType 
= "image/JPEG";    //返回jpg类型;
            using (Bitmap bitmap = new Bitmap(14080))  //像素大小;
            {
                
using (Graphics g = Graphics.FromImage(bitmap)) //生成一个画板
                {

                    Random rand 
= new Random();
                    
int code = rand.Next(1000999999);   //制定随机函数,用于限定字随机字符串大小;
                    string strCode = code.ToString();
                    HttpContext.Current.Session[
"Code"= strCode;   //在一般处理程序中使用Session接口;
                    g.Clear(Color.YellowGreen); //指定背景颜色;
                    g.DrawString(strCode, new Font("微输雅黑"20), Brushes.White, new PointF(1525));  //画的图片相关参数,(字体,大小),颜色,位置;
                    bitmap.Save(context.Response.OutputStream, ImageFormat.Jpeg);       //输出到流中并保存为jpg格式;
                }
            }
        }

        
public bool IsReusable
        {
            
get
            {
                
return false;
            }
        }
    }
}
原文地址:https://www.cnblogs.com/zhuiyi/p/2034874.html