1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
| class SecurityCode { private Random rand = new Random(); private string VerificationText = string.Empty; private Bitmap map; private int length; private int width; private int height;
public SecurityCode(int length, int width, int height) { this.length = length; this.width = width; this.height = height; }
public SecurityCode(int length) { this.length = length; this.width = (length + 1) * 25; this.height = 40; }
private void CreateVerificationText(int length) { VerificationText = string.Empty; string dictionary = "ABCDEFGHIJKLMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz23456789"; for (int i = 0; i < length; i++) { int index = rand.Next(0, dictionary.Length); VerificationText += dictionary[index].ToString(); } }
public void UpdateVerifyCode() { CreateVerificationText(length); CreateImage(); } private void CreateImage() { map = new Bitmap(width, height); Graphics g = Graphics.FromImage(map); Pen pen = new Pen(Color.Black); string[] font = { "Verdana", "Microsoft Sans Serif", "Consolas", "Arial", "宋体" }; Font f = new Font("Arial", 20, FontStyle.Bold); g.Clear(Color.White); SolidBrush brush = new SolidBrush(Color.White);
pen.Width = 0.1F; for (int i = 0; i < 15; i++) { pen.Color = RandColor(); g.DrawLine(pen, RandPoint(), RandPoint()); } for (int i = 0; i < 80; i++) { Point p = RandPoint(); map.SetPixel(p.X, p.Y, RandColor()); } SizeF StringSizeF = g.MeasureString(VerificationText, f); PointF StartPoint = new Point(0, (height - (int)StringSizeF.Height) / 2); for (int i = 0; i < length; i++) { brush.Color = RandColor(); int index = rand.Next(5); f = new Font(font[index], 20, FontStyle.Bold); StartPoint.X += 5; g.DrawString(VerificationText[i].ToString(), f, brush, StartPoint); SizeF CharSizeF = g.MeasureString(VerificationText[i].ToString(), f); StartPoint.X += CharSizeF.Width; } g.Dispose();
} private Color RandColor() { Color c = Color.FromArgb(rand.Next(1, 256), rand.Next(1, 255), rand.Next(1, 255)); return c; } private Point RandPoint() { int x = rand.Next(0, map.Width); int y = rand.Next(0, map.Height); return new Point(x, y); } public Bitmap getImage() { return map; } public string MD5Encrypt() { return Tool.MD5Encrypt(VerificationText); } public bool Check(string text) { return text.ToUpper().Equals(VerificationText.ToUpper()); } }
|