验证码

aspx页面验证码应用的常见处理方式

<%@ WebHandler Language="C#" Class="resImg" Debug="true"%>



using System;

using System.Web;

using System.Drawing;



public class resImg : IHttpHandler,System.Web.SessionState.IRequiresSessionState {//注意此处要实现 IRequireSessionState接口 要不然不能访问session



    public void ProcessRequest(HttpContext context)

    {

        context.Response.Clear();

        context.Response.ContentType = "image/jpeg";



        //从文件载入一个图像

        //Image img = Image.FromFile(context.Server.MapPath(@"blue hills.jpg")); 

        //Bitmap bmp = new Bitmap(img);

        //bmp.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);



        /*

         * 记得以前看C++ GDI绘图的时候讲过什么跟设备有关 跟设备无关

         * 可能这里意思就是说Bitmap跟设备有关,Graphics跟设备无关

         * 总之步骤就是:

         * 1创建一个Bitmap对象 并指定长宽

         * 2然后把一个Graphics往Bitmap对象上套,因为FromImage()里需要Image对象 而Bitmap继承自Image

         * 3然后用这个Graphics去绘图 其实 就是在先前创建的那个Bitmap对象 的“画布”上绘图

         * 4最后输出,依然使用Bitmap

         * 5收工

         */



        context.Session["valiCode"] = "hello"; 

        Bitmap bmp = new Bitmap(100, 100);

        Graphics graph = Graphics.FromImage(bmp);//graphics Bitmap继承自Image

        graph.DrawString("hello", new Font("宋体", 25), System.Drawing.Brushes.Red, new PointF(1, 1));

        bmp.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);

    }

 

    public bool IsReusable {

        get {

            return false;

        }

    }



}

你可能感兴趣的:(验证码)