CAPTCHA Image Custom Control

Jun 9 2008 3:18 PM
ok guys its clunky but it works lol. Still have a little issue though maybe you guys can help me with a solution or just tell me it cant be done either way.

anyway, I can display the image and if the user types in the captcha it will validate, however since i had to do a if (!Page.IsPostBack) in order for the captcha text not to override itself upon every Async post back it now wont refresh the image if someone clicks get new image.

is there a way i can make this Unaffected by anything causing a post back except my label button?

The Control shown below is being placed onto my Default.aspx page. and the lblbutton is named lbtnCaptchaRefresh.

if i remember right i cant cross name spaces in a custom control since the name space of the current project will never be the same between two projects.

I've also thought about using it as an embedded resources, but not sure how that would work on dynamically created images.

here is the code:


  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel;  
  4. using System.Text;  
  5. using System.Web;  
  6. using System.Web.UI;  
  7. using System.Web.UI.WebControls;  
  8. using System.Drawing;    
  9. using System.Drawing.Drawing2D;    
  10. using System.Drawing.Imaging;    
  11. using System.IO;  
  12. using System.Net;  
  13.   
  14. namespace Captcha  
  15. {  
  16.     [DefaultProperty("Text")]  
  17.     [ToolboxData("<{0}:Captcha runat=server></{0}:Captcha>")]  
  18.     public class Captcha : WebControl //IHttpHandler  
  19.     {  
  20.   
  21.         [Bindable(true)]  
  22.         [Category("Appearance")]  
  23.         [DefaultValue("")]  
  24.         [Localizable(true)]  
  25.           
  26.         /*public void ProcessRequest(HttpContext context) 
  27.         { 
  28.             BuildImage(context); 
  29.         } 
  30.          
  31.         public bool IsReusable 
  32.         { 
  33.             get { return true; } 
  34.         } 
  35.             */  
  36.   
  37.   
  38.   
  39.   
  40.   
  41.         public override Unit Width  
  42.         {  
  43.             get  
  44.             {  
  45.                 return base.Width;  
  46.             }  
  47.             set  
  48.             {  
  49.                 base.Width = 125;  
  50.             }  
  51.         }  
  52.               
  53.               
  54.             public override Unit Height  
  55.         {  
  56.             get  
  57.             {  
  58.                 return base.Height;  
  59.             }  
  60.             set  
  61.             {  
  62.                 base.Height = 125;  
  63.             }  
  64.         }  
  65.         int length = 5;  
  66.         [Description("The Length of the CAPTCHA Text")]  
  67.         public int CAPTCHALength  
  68.         {  
  69.             get  
  70.             {  
  71.                 return length;  
  72.             }  
  73.             set  
  74.             {  
  75.                 length = value;  
  76.             }  
  77.         }  
  78.         String backgroundstring = "";  
  79.         public string setbackgroundstring  
  80.         {  
  81.             get  
  82.             {  
  83.                 if (String.IsNullOrEmpty(backgroundstring))  
  84.                 {  
  85.                     backgroundstring = "-OCR-";  
  86.                     return backgroundstring;  
  87.                 }  
  88.                 else  
  89.                 {  
  90.                     return backgroundstring;  
  91.                 }  
  92.             }  
  93.             set  
  94.             {  
  95.                 backgroundstring = value;  
  96.             }  
  97.         }  
  98.         int CAPTCHAheight = 50;  
  99.         public int captchaheight  
  100.         {  
  101.             get  
  102.             {  
  103.                 return CAPTCHAheight;  
  104.             }  
  105.             set  
  106.             {  
  107.                 CAPTCHAheight = value;  
  108.             }  
  109.         }  
  110.         int CAPTCHAwidth = 150;  
  111.         public int captchawidth  
  112.         {  
  113.             get  
  114.             {  
  115.                 return CAPTCHAwidth;  
  116.             }  
  117.             set  
  118.             {  
  119.                 CAPTCHAwidth = value;  
  120.             }  
  121.         }  
  122.         int FONTSIZE = 40;  
  123.         public int fontsize  
  124.         {  
  125.             get  
  126.             {  
  127.                 return FONTSIZE;  
  128.             }  
  129.             set  
  130.             {  
  131.                 FONTSIZE = value;  
  132.             }  
  133.         }  
  134.         Color CAPTCHAFOREGROUNDCOLOR = Color.Gold;  
  135.         public Color captchaforegroundcolor  
  136.         {  
  137.             get  
  138.             {  
  139.                 return CAPTCHAFOREGROUNDCOLOR;  
  140.             }  
  141.             set  
  142.             {  
  143.                 CAPTCHAFOREGROUNDCOLOR = value;  
  144.             }  
  145.         }  
  146.         Color CAPTCHABACKGROUNDCOLOR = Color.Black;  
  147.         public Color captchabackgroundcolor  
  148.         {  
  149.             get  
  150.             {  
  151.                 return CAPTCHABACKGROUNDCOLOR;  
  152.             }  
  153.             set  
  154.             {  
  155.                 CAPTCHABACKGROUNDCOLOR = value;  
  156.             }  
  157.         }  
  158.         Color TEXTCOLOR1 = Color.GhostWhite;  
  159.         public Color primarytextcolor  
  160.         {  
  161.             get  
  162.             {  
  163.                 return TEXTCOLOR1;  
  164.             }  
  165.             set  
  166.             {  
  167.                 TEXTCOLOR1 = value;  
  168.             }  
  169.         }  
  170.         Color TEXTCOLOR2 = Color.Gold;  
  171.         public Color secondarytextcolor  
  172.         {  
  173.             get  
  174.             {  
  175.                 return TEXTCOLOR2;  
  176.             }  
  177.             set  
  178.             {  
  179.                 TEXTCOLOR2 = value;  
  180.             }  
  181.         }  
  182.         HatchStyle BACKGROUNDHATCHTYPE = HatchStyle.SmallConfetti;  
  183.         public HatchStyle setBackgroundHatchStyle  
  184.         {  
  185.             get  
  186.             {  
  187.                 return BACKGROUNDHATCHTYPE;  
  188.             }  
  189.             set  
  190.             {  
  191.                 BACKGROUNDHATCHTYPE = value;  
  192.             }  
  193.         }  
  194.         HatchStyle TEXTHACHTYPE = HatchStyle.Shingle;  
  195.         public HatchStyle setTextHatchStyle  
  196.         {  
  197.             get  
  198.             {  
  199.                 return TEXTHACHTYPE;  
  200.             }  
  201.             set  
  202.             {  
  203.                 TEXTHACHTYPE = value;  
  204.             }  
  205.         }  
  206.         String URL; String imageurl;  
  207.         [Description("Where you want to save the image")]  
  208.         public string savelocation  
  209.         {  
  210.             get  
  211.             {  
  212.                 return URL;  
  213.             }  
  214.             set  
  215.             {  
  216.                 URL = value;  
  217.             }  
  218.         }  
  219.         public string BuildImage()  
  220.         {  
  221.             Bitmap captchabmp = new Bitmap(CAPTCHAwidth, CAPTCHAheight);  
  222.             Graphics captchagraphic = Graphics.FromImage(captchabmp);  
  223.             Rectangle rect = new Rectangle(0, 0, CAPTCHAwidth, CAPTCHAheight);  
  224.             captchagraphic.FillRectangle(new HatchBrush(BACKGROUNDHATCHTYPE, CAPTCHAFOREGROUNDCOLOR, CAPTCHABACKGROUNDCOLOR), rect);  
  225.   
  226.             captchagraphic.SmoothingMode = SmoothingMode.AntiAlias;  
  227.   
  228.             string captchastr = "";  
  229.   
  230.             char[] captchaarray = new char[length];  
  231.   
  232.             int x;  
  233.   
  234.             Random rand = new Random();  
  235.             Random upperlower = new Random();  
  236.             Random captcha = new Random();  
  237.   
  238.             int z;  
  239.             int y;  
  240.             string temp;  
  241.             for (x = 0; x < length; x++)  
  242.             {  
  243.                 z = captcha.Next(0, 3);  
  244.                 if (z == 1)  
  245.                 {  
  246.                     captchaarray[x] = System.Convert.ToChar(rand.Next(65, 90));  
  247.                 }  
  248.                 else  
  249.                 {  
  250.                     captchaarray[x] = System.Convert.ToChar(rand.Next(49, 57));  
  251.                 }  
  252.             }  
  253.   
  254.             for (x = 0; x < length; x++)  
  255.             {  
  256.                 y = upperlower.Next(0, 99);  
  257.                 if (y >= 0 || y < 50)  
  258.                 {  
  259.                     temp = (captchaarray[x].ToString());  
  260.                     temp = temp.ToLower();  
  261.                     captchastr += temp.ToString();  
  262.                 }  
  263.                 else  
  264.                 {  
  265.                     temp = (captchaarray[x].ToString());  
  266.                     temp = temp.ToUpper();  
  267.                     captchastr += temp.ToString();  
  268.                 }  
  269.             }  
  270.              
  271.             #region Image Builder  
  272.             Random ranpoint = new Random();  
  273.             int fontStyle = (int)FontStyle.Italic;  
  274.             FontFamily family = new FontFamily("Arial");  
  275.             int emSize = FONTSIZE;  
  276.             Point origin = new Point(ranpoint.Next(rect.Width / 8), ranpoint.Next(rect.Height / 6));  
  277.             StringFormat format = StringFormat.GenericDefault;  
  278.   
  279.             GraphicsPath captchapath = new GraphicsPath();  
  280.             captchapath.AddString(captchastr, family, fontStyle, emSize, origin, format);  
  281.             float floatpoint = 6F;  
  282.             PointF[] randompoints =   
  283.             {  
  284.                 new PointF(ranpoint.Next(rect.Width) / floatpoint, ranpoint.Next(rect.Height) / floatpoint),   
  285.                 new PointF(rect.Width - ranpoint.Next(rect.Width)/floatpoint, ranpoint.Next(rect.Height) / floatpoint),  
  286.                 new PointF(ranpoint.Next(rect.Width)/ floatpoint, rect.Height - ranpoint.Next(rect.Height) / floatpoint),  
  287.                 new PointF(rect.Width - ranpoint.Next(rect.Width) / floatpoint, rect.Height - ranpoint.Next(rect.Height) / floatpoint)  
  288.             };  
  289.             Matrix captchamatrix = new Matrix();  
  290.             captchamatrix.Translate(2F, 4F);  
  291.             captchapath.Warp(randompoints, rect, captchamatrix, WarpMode.Perspective, 25F);  
  292.             Font captchafont2 = new Font("Ariel", FONTSIZE);  
  293.   
  294.             captchagraphic.DrawString(backgroundstring, captchafont2, Brushes.Black, (rect.Width / 6), (rect.Height / 6));  
  295.             captchagraphic.DrawCurve(new Pen(CAPTCHAFOREGROUNDCOLOR, 2), randompoints);  
  296.             HatchBrush captchafont = new HatchBrush(TEXTHACHTYPE, Color.GhostWhite, Color.Gold);  
  297.             captchagraphic.FillPath(captchafont, captchapath);  
  298.  
  299.             #endregion  
  300.               
  301.               
  302.             Random randomurlgenerator = new Random();  
  303.             String randomurl = randomurlgenerator.Next(1, 10).ToString();  
  304.             for (int i = 0; i < 15; i++)  
  305.             {  
  306.                 randomurl += randomurlgenerator.Next(1, 10);  
  307.             }  
  308.   
  309.             String IMAGE = randomurl + "CAPTCHA.Jpg";  
  310.             imageurl = URL + IMAGE;   
  311.               
  312.               
  313.             captchafont.Dispose();  
  314.             captchafont2.Dispose();  
  315.             captchagraphic.Dispose();  
  316.             try  
  317.             {  
  318.                 captchabmp.Save(imageurl, ImageFormat.Jpeg);  
  319.             }  
  320.             catch (Exception ex)  
  321.             {  
  322.                 Context.Response.Write(ex.ToString());  
  323.             }  
  324.             HttpContext.Current.Session.Add("CaptchaURL", IMAGE);  
  325.             HttpContext.Current.Session.Add("captchastr", captchastr);  
  326.               
  327.             //HttpContext.Current.Session.Add("captchastr", captchastr);  
  328.             /*MemoryStream ms = new MemoryStream(); 
  329.             Context.Response.Clear(); 
  330.             Context.Response.ContentType = "image/jpeg"; 
  331.             captchabmp.Save(ms, ImageFormat.Jpeg); 
  332.             ms.WriteTo(Context.Response.OutputStream);*/  
  333.   
  334.             captchabmp.Dispose();  
  335.               
  336.   
  337.             return imageurl;  
  338.         }  
  339.         protected override void OnInit(EventArgs e)  
  340.         {  
  341.             base.OnInit(e);  
  342.             if (!Page.IsPostBack)  
  343.             {  
  344.                 BuildImage();  
  345.             }  
  346.               
  347.         }  
  348.           
  349.         protected override void Render(HtmlTextWriter writer)  
  350.         {  
  351.   
  352.               
  353.             writer.RenderBeginTag("img src=\"" + imageurl + "\"");  
  354.             writer.RenderEndTag();  
  355.   
  356.             base.Render(writer);  
  357.               
  358.         }  
  359.   
  360.          
  361.     }