using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Text;

namespace SystemScan
{
  public class Recaptcha
  {
    private Random rand;

    public Bitmap CreateImage(out string code)
    {
      try
      {
        code = this.GetRandomText();
        Bitmap bitmap = new Bitmap(200, 50, PixelFormat.Format32bppArgb);
        Graphics g = Graphics.FromImage((Image) bitmap);
        Pen pen = new Pen(Color.Yellow);
        Rectangle rect = new Rectangle(0, 0, 200, 50);
        SolidBrush solidBrush1 = new SolidBrush(Color.Maroon);
        SolidBrush solidBrush2 = new SolidBrush(Color.White);
        int num = 0;
        g.DrawRectangle(pen, rect);
        g.FillRectangle((Brush) solidBrush1, rect);
        for (int index = 0; index < code.Length; ++index)
        {
          g.DrawString(code[index].ToString(), new Font("verdana", (float) (8 + new Random().Next(14, 18))), (Brush) solidBrush2, new PointF((float) (8 + num), 10f));
          num += 20;
        }
        this.DrawRandomLines(g);
        return bitmap;
      }
      catch (Exception ex)
      {
        code = string.Empty;
        return (Bitmap) null;
      }
    }

    private void DrawRandomLines(Graphics g)
    {
      SolidBrush solidBrush = new SolidBrush(Color.Yellow);
      for (int index = 0; index < 20; ++index)
        g.DrawLines(new Pen((Brush) solidBrush, 2f), this.GetRandomPoints());
    }

    private Point[] GetRandomPoints()
    {
      this.rand = new Random();
      Point[] pointArray = new Point[2];
      int index1 = 0;
      Point point1 = new Point(this.rand.Next(1, 150), this.rand.Next(1, 150));
      pointArray[index1] = point1;
      int index2 = 1;
      Point point2 = new Point(this.rand.Next(1, 100), this.rand.Next(1, 100));
      pointArray[index2] = point2;
      return pointArray;
    }

    private string GetRandomText()
    {
      string str1 = string.Empty;
      StringBuilder stringBuilder = new StringBuilder();
      if (string.IsNullOrEmpty(str1))
      {
        string str2 = "abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        Random random = new Random();
        for (int index = 0; index <= 5; ++index)
          stringBuilder.Append(str2[random.Next(str2.Length)]);
        str1 = stringBuilder.ToString();
      }
      return str1;
    }
  }
}
this.picCaptcha.Image = (Image) new Recaptcha().CreateImage(out this.strCaptcha);

if (this.strCaptcha != this.txtCaptcha.Text)
      {
        int num = (int) MessageBox.Show("Text entered did not match with text in image");
        this.picCaptcha.Image = (Image) new Recaptcha().CreateImage(out this.strCaptcha);
        this.txtCaptcha.Text = "";
        this.txtCaptcha.Focus();
      }

  

posted on 2019-09-05 10:30  站在那看风景  阅读(132)  评论(0编辑  收藏  举报