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