2009/11/09

[C#]My simple version of Captcha

This is my own version of Captcha. It's easy and simple. You can improve it with your ideas or needs.
using (Bitmap bmp = new Bitmap(90, 30))
{
  int x1 = 0;
  int y1 = 0;
  int x2 = 0;
  int y2 = 0;
  int x3 = 0;
  int y3 = 0;
  int intNoiseWidth = 25;
  int intNoiseHeight = 15;
  Random rdn = new Random();
  Graphics g = Graphics.FromImage(bmp);

  //set the font style
  Font font = new Font("Courier New", 12, FontStyle.Bold);

  //set the image background
  g.Clear(Color.Cornsilk);

  //generate random dots
  for (int i = 0; i < 80; i++)
  {
    x1 = rdn.Next(0, bmp.Width);
    y1 = rdn.Next(0, bmp.Height);
    bmp.SetPixel(x1, y1, Color.Brown);
  }

  //generate random arcs
  for (int i = 0; i < 15; i++)
  {
    x1 = rdn.Next(bmp.Width - intNoiseWidth);
    y1 = rdn.Next(bmp.Height - intNoiseHeight);
    x2 = rdn.Next(1, intNoiseWidth);
    y2 = rdn.Next(1, intNoiseHeight);
    x3 = rdn.Next(0, 45);
    y3 = rdn.Next(-270, 270);
    g.DrawArc(new Pen(Brushes.Gray), x1, y1, x2, y2, x3, y3);
  }

  //replace the GenPassword() method with your own password creator
  //remember to keep the string that you just generated in order to compare with the user's input
  g.DrawString(GenPassword(6), font, Brushes.Black, 3, 3);

  //you can either save it to a file, or directly output it to your web page
  bmp.Save(@"C:\Temp\Captcha.gif", ImageFormat.Gif);
}

No comments:

Post a Comment