Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Image Recaptcha using Generic Handler

0.00/5 (No votes)
18 Oct 2013 1  

This articles was originally at wiki.asp.net but has now been given a new home on CodeProject. Editing rights for this article has been set at Bronze or above, so please go in and edit and update this article to keep it fresh and relevant.

Generic handler for captcha image generation:
<%@ WebHandler Language="C#" Class="CaptchaHandler" %> 
    using System; 
    using System.Web; 
    using System.Drawing; 
    using System.Drawing.Text; 
    using System.Drawing.Imaging; 
    using System.Drawing.Drawing2D; 
    using System.IO; 
    using System.Web.SessionState;


public class CaptchaHandler : IHttpHandler, IRequiresSessionState
    {
        public void ProcessRequest(HttpContext context)
        {
            using (Bitmap b = new Bitmap(250, 50))
            {
                Font f = new Font("Arial Black", 20F);
                Graphics g = Graphics.FromImage(b);
                SolidBrush whiteBrush = new SolidBrush(Color.Black);
                SolidBrush blackBrush = new SolidBrush(Color.White);
                RectangleF canvas = new RectangleF(0, 0, 250, 50);
                g.FillRectangle(whiteBrush, canvas);
                context.Session["Captcha"] = GetRandomString();
                g.DrawString(context.Session["Captcha"].ToString(), f, blackBrush, canvas);
                context.Response.ContentType = "image/gif";
                b.Save(context.Response.OutputStream, ImageFormat.Gif);
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        private string GetRandomString()
        {
            string[] arrStr = "A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,A,R,S,T,U,V,W,X,Y,Z,1,2,3,4,5,6,7,8,9,0".Split(",".ToCharArray());
            string strDraw = string.Empty;
            Random r = new Random();
            for (int i = 0; i < 5; i++)
            {
                strDraw += arrStr[r.Next(0, arrStr.Length - 1)];
            }
            return strDraw;
        }
    }

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here