Winform验证码工具

一、生成验证码并产生图片

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
public class ValidateCodeCreator
{
/// <summary>
/// 产生验证码
/// </summary>
/// <param name="codeLength">验证码长度</param>
/// <returns></returns>
public string CreateCode(int codeLength)
{
string so = "1,2,3,4,5,6,7,8,9,0,a,b,c,d,e,f,g,h,i,j,k,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z";
string[] strArr = so.Split(',');
string code = "";
Random rand = new Random();
for (int i = 0; i < codeLength; i++)
{
code += strArr[rand.Next(0, strArr.Length)];
}
return code;
}
/// <summary>
/// 产生验证图片
/// </summary>
/// <param name="code"></param>
public byte[] CreateCodeImage(string code)
{
Bitmap image = new Bitmap(code.Length * 22, 30);
Graphics g = Graphics.FromImage(image);
Random r = new Random();
try
{
WebColorConverter ww = new WebColorConverter();
string[] backgroundcolor = { "#F8F8FF", "#BBFFFF", "#E6E6FA", "#CAE1FF", "#FFFACD", "#B0E2FF" };
g.Clear((Color)ww.ConvertFromString(backgroundcolor[r.Next(0,5)]));
//数组存放字体
string[] fonts = { "黑体", "微软雅黑", "隶书", "楷体" };
//数组存放颜色
Color[] codecolors = { Color.Red, Color.Black, Color.Blue, Color.Purple, Color.DarkGoldenrod, Color.Magenta, Color.Khaki };
Color[] linecolors = { Color.Green, Color.DarkGreen, Color.SeaGreen, Color.DarkSlateBlue };
//画字
for (int i = 0; i < code.Length; i++)
{
//指定座标
Point p = new Point(i * 20, 0);
//画文字
g.DrawString(code[i].ToString(), new Font(fonts[r.Next(0,3)], 20, FontStyle.Italic), new SolidBrush(codecolors[r.Next(0,6)]), p);
}
//画线
int linecolormk = r.Next(0, 3);
for (int j = 0; j < 12; j++)
{
Point p1 = new Point(r.Next(0, image.Width), r.Next(image.Height));
Point p2 = new Point(r.Next(0, image.Width), r.Next(0, image.Height));
g.DrawLine(new Pen(linecolors[linecolormk]), p1, p2);
}
//画像素点
for (int i = 0; i < 100; i++)
{
Point p1 = new Point(r.Next(0, image.Width), r.Next(image.Height));
Point p2 = new Point(r.Next(0, image.Width), r.Next(0, image.Height));
image.SetPixel(p1.X, p1.Y, Color.Black);
}
MemoryStream ms = new MemoryStream();
image.Save(ms, ImageFormat.Gif);
return ms.ToArray();
}
finally
{
g.Dispose();
image.Dispose();
}
}

二、验证码刷新

1
2
3
4
5
6
private void refreshcode()
{
ValidateCodeCreator a = new ValidateCodeCreator();
string code = a.CreateCode(6);
pictureBox1.Image = ByteToImage(a.CreateCodeImage(code));
}

三、byte转image

1
2
3
4
5
6
7
8
private System.Drawing.Image ByteToImage(byte[] btImage)
{
if (btImage.Length == 0)
return null;
System.IO.MemoryStream ms = new System.IO.MemoryStream(btImage);
System.Drawing.Image image = System.Drawing.Image.FromStream(ms);
return image;
}