.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
 
Sign In
Register
 
Win Surprise Gifts!!!
Congratulations!!!


Top 5 Contributors of the Month
david stephan

Home >> Code Snippets >> ASP.NET Controls >> Post New Resource Bookmark and Share   

 Subscribe to Code Snippets

Captcha Generation in ASP.NET

Posted By:Athira Sreejith       Posted Date: February 22, 2009    Points: 10    Category: ASP.NET Controls    URL: http://www.dotnetspark.com  
 

Capcha Generation in ASP.NET. Now a days captcha is must for all the website which requires the user interaction to avoid spam registration or to avoid spam comment. Captcha is one of the solution to prevent spam.

In this a image is generated programmatically and user has to enter the text displayed in image.
You might have seen captcha in almost all the blog.

Below is the simple example to create your own captcha in asp.net. Like this


 

C# Code Example

using System;

using System.Data;

using System.Configuration;

using System.Collections;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

using System.Drawing.Imaging;

using System.Drawing;

using System.IO;

using System.Text;

public partial class captchageneration : System.Web.UI.Page
{
   
   
    private Random rand = new Random();
   
    protected void Page_Load(object sender, EventArgs e)
    {
       
       
        if (!IsPostBack) {
           
           
           
            CreateImage();
        }
       
    }
   
    public void CreateImage()
    {
       
       
        string code = GetRandomText();
       
       
        Bitmap bitmap = new Bitmap(150, 50, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
       
        Graphics g = Graphics.FromImage(bitmap);
       
        Pen pen = new Pen(Color.Yellow);
       
        Rectangle rect = new Rectangle(0, 0, 150, 50);
       
        SolidBrush b = new SolidBrush(Color.Cornsilk);
       
        SolidBrush blue = new SolidBrush(Color.Maroon);
       
        int counter = 0;
       
        g.DrawRectangle(pen, rect);
       
        g.FillRectangle(b, rect);
       
        for (int i = 0; i <= code.Length - 1; i++) {
           
           
           
           
            g.DrawString(code(i).ToString(), new Font("Verdena", 10 + rand.Next(14, 18)), blue, new PointF(10 + counter, 10));
           
           
            counter += 20;
        }
       
        //DrawRandomLines(g);
       
        Response.ContentType = "image/gif";
       
        bitmap.Save(Response.OutputStream, ImageFormat.Gif);
       
        g.Dispose();
       
       
        bitmap.Dispose();
    }
   
    private string GetRandomText()
    {
       
       
        StringBuilder randomText = new StringBuilder();
       
        if (Session("Code") == null) {
           
           
            string alphabets = "abcdefghijklmnopqrstuvwxyz";
           
            Random r = new Random();
           
            for (int j = 0; j <= 5; j++) {
               
               
               
                randomText.Append(alphabets(r.Next(alphabets.Length)));
            }
           
           
            Session("Code") = randomText.ToString();
        }
       
       
        return Session("Code") as String;
    }
   
    private void DrawRandomLines(Graphics g)
    {

        SolidBrush green = new SolidBrush(Color.Green);
       
        for (int i = 0; i <= 19; i++) {
           
           
           
            g.DrawLines(new Pen(green, 2), GetRandomPoints());
        }
       
    }
   
    private Point[] GetRandomPoints()
    {

       
        Point[] points = { new Point(rand.Next(10, 150), rand.Next(10, 150)), new Point(rand.Next(10, 100), rand.Next(10, 100)) };
       
       
        return points;
    }
   
}

 

And this is the similar code in VB.NET.

Imports System

Imports System.Data

Imports System.Configuration

Imports System.Collections

Imports System.Web

Imports System.Web.Security

Imports System.Web.UI

Imports System.Web.UI.WebControls

Imports System.Web.UI.WebControls.WebParts

Imports System.Web.UI.HtmlControls

Imports System.Drawing.Imaging

Imports System.Drawing

Imports System.IO

Imports System.Text

Public Partial Class captchageneration
    Inherits System.Web.UI.Page
   
   
    Private rand As New Random()
   
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
       
       
        If Not IsPostBack Then
           
           
           
            CreateImage()
           
        End If
    End Sub
   
    Public Sub CreateImage()
       
       
        Dim code As String = GetRandomText()
       
       
        Dim bitmap As New Bitmap(150, 50, System.Drawing.Imaging.PixelFormat.Format32bppArgb)
       
        Dim g As Graphics = Graphics.FromImage(bitmap)
       
        Dim pen As New Pen(Color.Yellow)
       
        Dim rect As New Rectangle(0, 0, 150, 50)
       
        Dim b As New SolidBrush(Color.Cornsilk)
       
        Dim blue As New SolidBrush(Color.Maroon)
       
        Dim counter As Integer = 0
       
        g.DrawRectangle(pen, rect)
       
        g.FillRectangle(b, rect)
       
        For i As Integer = 0 To code.Length - 1
           
           
           
           
            g.DrawString(code(i).ToString(), New Font("Verdena", 10 + rand.[Next](14, 18)), blue, New PointF(10 + counter, 10))
           
           
            counter += 20
        Next
       
        'DrawRandomLines(g);
       
        Response.ContentType = "image/gif"
       
        bitmap.Save(Response.OutputStream, ImageFormat.Gif)
       
        g.Dispose()
       
       
        bitmap.Dispose()
    End Sub
   
    Private Function GetRandomText() As String
       
       
        Dim randomText As New StringBuilder()
       
        If Session("Code") Is Nothing Then
           
           
            Dim alphabets As String = "abcdefghijklmnopqrstuvwxyz"
           
            Dim r As New Random()
           
            For j As Integer = 0 To 5
               
               
               
                randomText.Append(alphabets(r.[Next](alphabets.Length)))
            Next
           
           
            Session("Code") = randomText.ToString()
        End If
       
       
        Return TryCast(Session("Code"), [String])
    End Function
   
    Private Sub DrawRandomLines(ByVal g As Graphics)
       
       
        Dim green As New SolidBrush(Color.Green)
       
        For i As Integer = 0 To 19
           
           
           
            g.DrawLines(New Pen(green, 2), GetRandomPoints())
           
        Next
    End Sub
   
    Private Function GetRandomPoints() As Point()
       
       
       
       
       
        Dim points As Point() = {New Point(rand.[Next](10, 150), rand.[Next](10, 150)), New Point(rand.[Next](10, 100), rand.[Next](10, 100))}
       
       
        Return points
    End Function
   
End Class

And if you run the above code you will get captcha image like the above displayed image



     

Further Readings:

Responses

No response found. Be the first to respond this post

Post Comment

You must Sign In To post reply
Find More code samples in C#, ASP.Net, Vb.Net and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend