Tuesday 22 October 2013

Create a Captcha and change it on refresh using IHttpHandler

What is Captcha ?
    Captcha is the information that is used to find whether in the end user an client is working or an robotic program is running. Few months back i tried a few samples to create program for automatic download from a FTP Server if any file exists. The thing is the automatic program is works fine download the file FTP server and save it to send as message to Phone. Now here i taken a Free domain which is providing a FTP server as Free. After testing the program i make a Windows service do that code to run after every 10 seconds to file the file in FTP to download. After successful in Testing i Left the computer as it is , When i came back evening to home and checked mail. I received a mail from that Domain Administration that "In the Past one hour more than 10,000 request hit my server due that my server got down i can't start the FTP Server Due to that currently we are disable the account for access." 

above scenario is the one of the robotic information to avoid this Captcha is used, make the user to enter the code which is seen is image and validate it .

Initially Captcha is made as clear image by stating characters alone , but some developers make than entry also automatic and make the request as Robotic , That's y today the captcha is very cricitical to understand so easily by giving background some diagonals, Change in Fonts for each character and difference in charcters shape etc.


How the developers make Captcha also in Robotic , Thats simple they read the image and Find the Letters Present inside the image and supply that to the textbox programmatically, how this can be done using OCR technology.

Read about OCR Click here OCR

In this example we are creating a Httphandler, Which will handle the request from the end user and return back the image to the user




How  create the Create generate the Random Numbers conver them in to image.

Handler Code :


using System;
using System.Web;
using System.Collections.Generic;
using System.Drawing;

public class GetImgTextHandler : IHttpHandler
{

    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "image/jpeg";
        var CaptchaText = context.Request.QueryString["code"];


        HttpContext.Current.Application["Code"] = CaptchaText;
        if (CaptchaText != null)
        {
            List<Letter> letter = new List<Letter>();
            int TotalWidth = 0;
            int MaxHeight = 0;
            foreach (char c in CaptchaText)
            {
                var ltr = new Letter(c);
                letter.Add(ltr);
                int space = (new Random()).Next(5) + 1;
                ltr.space = space;
                System.Threading.Thread.Sleep(1);
                TotalWidth += ltr.LetterSize.Width + space;
                if (MaxHeight < ltr.LetterSize.Height)
                    MaxHeight = ltr.LetterSize.Height;
                System.Threading.Thread.Sleep(1);
            }
            const int HMargin = 5;
            const int VMargin = 3;

            Bitmap bmp = new Bitmap(TotalWidth + HMargin, MaxHeight + VMargin);
            var Grph = Graphics.FromImage(bmp);
            Grph.FillRectangle(new SolidBrush(Color.Lavender), 0, 0, bmp.Width, bmp.Height);
            Pixelate(ref bmp);
            Grph.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
            Grph.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            int xPos = HMargin;
            foreach (var ltr in letter)
            {
                Grph.DrawString(ltr.letter.ToString(), ltr.font, new SolidBrush(Color.White), xPos, VMargin);
                xPos += ltr.LetterSize.Width + ltr.space;
            }

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

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

    private void Pixelate(ref Bitmap bmp)
    {
        Color[] Colors = { Color.Gray, Color.Red, Color.Blue, Color.Olive };
        for (int i = 0; i < 200; i++)
        {
            var rnd = new Random(DateTime.Now.Millisecond);
            var grp = Graphics.FromImage(bmp);
            Image background = Image.FromFile(HttpContext.Current.Server.MapPath("~/images/captcha.gif"));
            grp.DrawImage(background, new Rectangle(0, 0, bmp.Width, bmp.Height));
        }
    }

}





public class Letter
{
    string[] ValidFonts = { "Segoe Script", "Century", "Eccentric Std", "Freestyle Script", "Viner Hand ITC" };
    public Letter(char c)
    {
        Random rnd = new Random();
        font = new Font(ValidFonts[rnd.Next(ValidFonts.Count() - 1)], rnd.Next(20) + 20, GraphicsUnit.Pixel);
        letter = c;
    }
    public Font font
    {
        get;
        private set;
    }
    public Size LetterSize
    {
        get
        {
            var Bmp = new Bitmap(1, 1);
            var Grph = Graphics.FromImage(Bmp);
            return Grph.MeasureString(letter.ToString(), font).ToSize();
        }
    }
    public char letter
    {
        get;
        private set;
    }
    public int space
    {
        get;
        set;
    }

}


Code in Html :


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="Scripts/jquery-1.9.1.js"></script>
    <script>


        function Change() {
            var img = document.getElementById("captcha");
            var randomnumber = Math.random().toString();
            var code = randomnumber.substring(3, 9);
            img.src = "GetImgTextHandler.ashx?code=" + code;


        }

      
 $(document).ready(function () {

            var img = document.getElementById("captcha");
            var randomnumber = Math.random().toString();
            var code = randomnumber.substring(3, 9);
            img.src = "GetImgTextHandler.ashx?code=" + code;



        });
    </script>
</head>
<body>
<fieldset style="width:300px" align="center">
<legend>Generate Captcha</legend>
 
  <table>
 
  <tr><td></td><td> <img src="" id="captcha" height="35px" width="155px" /> <a href="#" onclick="Change()" >change</a></td></tr>
  <tr><td> Enter Code : </td><td><input type="text" name="txt" /></td></tr>
  </table>

 
</fieldset>
         


</body>
</html>




I hope From this article you can learn how to create your own Captcha using the HttpHandler.



No comments:

Post a Comment