65.9K
CodeProject is changing. Read more.
Home

Image Recaptcha using Generic Handler

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.80/5 (2 votes)

Oct 11, 2013

CPOL
viewsIcon

15785

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;
        }
    }