using System; using System.Data; using System.Configuration; 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; using System.Drawing.Imaging;
public class Captcha { private System.Drawing.Image image;//generated image private int width, height; //width,height of the image to be generated private string text = ""; //code private Random random;//for random number generation
public Captcha(int w, int h, string text) { width = w; height = h; random = new Random(); this.text = text; this.GenerateImage(); } public System.Drawing.Image CapImage { get { return image; } }
// returns the Randomly generated String public static string GenerateRandomCode() { int no = 0; string no1 = ""; Random r = new Random(); no = r.Next(10); no = no * 10 + r.Next(10); no = no * 10 + r.Next(10);
char c = (char)r.Next(65, 90); char c1 = (char)r.Next(65, 90); no = no * 10 + r.Next(10); //Convert all number into String no1 = no.ToString();
//Insert the two character into the specified position no1 = no1.Insert(0, c.ToString()); no1 = no1.Insert(2, c1.ToString()); return no1.ToString(); }
private void GenerateImage() { // Create a bitmap image. Bitmap bitmap = new Bitmap(this.width, this.height); // Create a graphics object for drawing. Graphics g = Graphics.FromImage(bitmap); //Create Rect Rectangle rect = new Rectangle(0, 0, this.width - 1, this.height - 1);
//Create Font Font font = new Font("Arial", width / 8, FontStyle.Italic); // Fill in the background. g.FillRectangle(Brushes.SeaShell, rect); // Set up the text format. StringFormat format = new StringFormat(); format.Alignment = StringAlignment.Center; format.LineAlignment = StringAlignment.Center; //Rotation angle g.RotateTransform(5); //Draw the Text g.DrawString(this.text, font, Brushes.Sienna, rect, format); // Add some random noise. int m = Math.Max(rect.Width, rect.Height); for (int i = 0; i < (int)(rect.Width * rect.Height / 20); i++) { int x = this.random.Next(rect.Width); int y = this.random.Next(rect.Height); int w = this.random.Next(m / 50); int h = this.random.Next(m / 50); g.FillEllipse(Brushes.Gray, x, y, w, h); } // Clean up. g.Dispose(); // Set the image. this.image = bitmap; } }
|