Generate captcha in .Net
Net has powerful language features so many people use this language to achieve extremely fast development tasks, and now we are concerned about how to use .Net to generate captcha. In fact, it will generate captcha in several steps, the picture space, draw text, marked with noise, then output image, the process is too simple in .net. The code:
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Drawing;
namespace SessionCode
{
public partial class checkimage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
GetCode();
}
protected void GetCode()
{
System.Random rand = new Random();
char[] chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray();
System.Text.StringBuilder myStr = new System.Text.StringBuilder();
for (int iCount = 0; iCount < len; iCount++)
{
myStr.Append(chars[rand.Next(chars.Length)]);
}
string text = myStr.ToString();
Size ImageSize = Size.Empty;
using (Bitmap bmp = new Bitmap(5, 5))
{
using (Graphics g = Graphics.FromImage(bmp))
{
SizeF size = g.MeasureString(text, myFont, 10000);
ImageSize.Width = (int)size.Width + 3;
ImageSize.Height = (int)size.Height + 3;
}
}
using (Bitmap bmp = new Bitmap(ImageSize.Width, ImageSize.Height))
{
{
g.Clear(Color.White);
using (StringFormat f = new StringFormat())
{
f.Alignment = StringAlignment.Near;
f.LineAlignment = StringAlignment.Center;
f.FormatFlags = StringFormatFlags.NoWrap;
g.DrawString(text, myFont, Brushes.Black, new RectangleF (0, 0, ImageSize.Width, ImageSize.Height), f);
}
}
int num = ImageSize.Width * ImageSize.Height * 20 / 100;
for (int iCount = 0; iCount < num; iCount++)
{
int x = rand.Next(ImageSize.Width);
int y = rand.Next(ImageSize.Height);
int r = rand.Next(255);
int g = rand.Next(255);
int b = rand.Next(255);
Color c = Color.FromArgb(r, g, b);
bmp.SetPixel(x, y, c);
}
System.IO.MemoryStream ms = new System.IO.MemoryStream();
bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
this.Response.ContentType = "image/png";
ms.WriteTo(this.Response.OutputStream);
ms.Close();
}
myFont.Dispose();
}
}
}
Successful programming language is not without reason, neat and quick to put these things done, you have to say it to be high efficiency, the above code is also very easy to understand, but also a lot of comment. If you have a better code, welcomed the exchange withKnowCaptcha.
Recommended reading: 1.Generate CAPTCHA image in Java; 2.How to produce XBM Captcha using ASP; 3.How to generate a more difficult Captcha Image.











