Create Captcha using C#

Step 1: Create aspx page GenerateCaptcha.aspx.

Step 2: In the code behind write the below code; 

  1. Response.Clear();  
  2. int height = 30;  
  3. int width = 100;  
  4. Bitmap bmp = new Bitmap(width, height);  
  5. RectangleF rectf = new RectangleF(20, 5, 0, 0);  
  6. Graphics g = Graphics.FromImage(bmp);  
  7. g.Clear(Color.White);  
  8. g.SmoothingMode = SmoothingMode.AntiAlias;  
  9. g.InterpolationMode = InterpolationMode.HighQualityBicubic;  
  10. g.PixelOffsetMode = PixelOffsetMode.HighQuality;  
  11. g.DrawString(Session["captcha"].ToString(), new Font("Thaoma", 15, FontStyle.Strikeout), Brushes.Green, rectf);  
  12. g.DrawRectangle(new Pen(Brushes.LemonChiffon), 1, 1, width - 8, height - 2);  
  13. g.Flush();  
  14. Response.ContentType = "image/jpeg";  
  15. bmp.Save(Response.OutputStream, ImageFormat.Jpeg);  
  16. g.Dispose();  
  17. bmp.Dispose();  
Step 3: Where you want to show captcha copy paste the below code,
  1. <asp:UpdatePanel ID="UP1" runat="server">  
  2.     <ContentTemplate>  
  3.         <asp:Image ID="imgCaptcha" runat="server" />  
  4.         <asp:LinkButton ID="lbtnRefresh" CssClass="btn btn-info" runat="server" OnClick="btnRefresh_Click"><span class="glyphicon glyphicon-refresh"></span> Refresh</asp:LinkButton>  
  5.     </ContentTemplate>  
  6. </asp:UpdatePanel>  
Step 4: In code behind make the function below and call on page load,
  1. void FillCapctha()  
  2. {  
  3.     try  
  4.     {  
  5.         Random random = new Random();  
  6.         string combination = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";  
  7.         StringBuilder captcha = new StringBuilder();  
  8.         for (int i = 0; i < 6; i++)  
  9.             captcha.Append(combination[random.Next(combination.Length)]);  
  10.         Session["captcha"] = captcha.ToString();  
  11.         imgCaptcha.ImageUrl = "~/Captcha/GenerateCaptcha.aspx?" + DateTime.Now.Ticks.ToString();  
  12.     } catch  
  13.     {  
  14.         throw;  
  15.     }  
  16. }  
Step 5: On click of refresh button call function FillCapctha().