Example Of Generate Captcha code using asp.net with C#
Default.aspx
<%@ Page Language="C#"
AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!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 runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Image ID="Image1" runat="server" Width="75px" Height="150px" ImageUrl="~/Default.aspx" /><br />
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><br />
<asp:Button ID="Button1" runat="server" Text="submit" onclick="Button1_Click" />
</div>
</form>
</body>
</html>
Default.aspx.cs
using System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Web;
using
System.Web.UI;
using
System.Web.UI.WebControls;
using
System.Drawing;
using
System.Drawing.Drawing2D;
using
System.Drawing.Text;
using
System.Drawing.Imaging;
using System.IO;
using
System.Text;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object
sender, EventArgs e)
{
if
(!Page.IsPostBack)
{
Session["captcha"]
= null;
createcapimage();
// getrandomtext();
}
}
private void createcapimage()
{
string
code=null;
code=getrandomtext();
Bitmap
bt = new Bitmap(200,60,System.Drawing.Imaging.PixelFormat.Format32bppPArgb);
Graphics
gr = Graphics.FromImage(bt);
Pen
pen = new Pen(Color.Yellow);
Rectangle
displrec = new Rectangle(0,0,200,60);
SolidBrush
blu = new SolidBrush(Color.CornflowerBlue);
SolidBrush
black = new SolidBrush(Color.Black);
int
couter= 0;
gr.DrawRectangle(pen, displrec);
gr.FillRectangle(blu, displrec);
for (int i = 0; i < code.Length; i++)
{
Random
rd = new Random();
gr.DrawString(code[i].ToString(), new Font("Tahoma", 10 + rd.Next(15, 20), FontStyle.Italic), black, new
PointF(10 + couter, 10));
couter += 28;
}
drawrandomline(gr);
bt.Save(Response.OutputStream, ImageFormat.Jpeg);
// gr.Dispose();
//bt.Dispose();
}
private string getrandomtext()
{
StringBuilder
randomText = new StringBuilder();
string
alph = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
Random
r = new Random();
for (int j = 0; j <= 5; j++)
{
randomText.Append(alph[r.Next(alph.Length)]);
}
Session["captcha"]
= randomText.ToString();
return
Session["captcha"] as String;
}
private void drawrandomline(Graphics
g)
{
SolidBrush
yellow = new SolidBrush(Color.Yellow);
for (int i = 0; i < 20; i++)
{
g.DrawLines(new Pen(yellow, 1),
getrandompoint());
}
}
private Point[] getrandompoint()
{
Random
r = new Random();
Point[]
points = { new Point(r.Next(0,
150), r.Next(1, 150)), new Point(r.Next(0, 200), r.Next(1, 190)) };
return
points;
}
protected void Button1_Click(object
sender, EventArgs e)
{
string
captch = Session["captcha"].ToString();
if
((captch.Equals(TextBox1.Text)))
{
TextBox1.Text = "good one";
}
else
{
TextBox1.Text = "Sorry !!";
}
}
}
0 comments :