算法验证码

加法乘法验证码

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
protected void (object sender, EventArgs e)
{
Color[] color = { Color.Black, Color.Red, Color.Blue, Color.Brown, Color.DarkBlue, Color.Yellow, Color.Green };
string[] font = { "宋体", "新宋体", "幼圆", "楷体_GB2312", "黑体", "隶书" };
int[] fontsize = { 20, 40 };
int[] shuzi = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int[] shuzi2 = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

string[] fuhao = { "+", "*" };

Random rnd = new Random();
string fuhao1 = fuhao[rnd.Next(fuhao.Length)];
int chkCode = shuzi[rnd.Next(shuzi.Length)];
int chkCode2 = shuzi2[rnd.Next(shuzi2.Length)];
Bitmap bmp = new Bitmap(200, 100);
Graphics g = Graphics.FromImage(bmp);
g.Clear(Color.WhiteSmoke);

string f = fuhao1;
Session["ValidateCode3"] = f;
int s = chkCode;
int s2 = chkCode2;


if (fuhao1.ToString() == "+")
{
int sum = chkCode + chkCode2;
Session["ValidateCode1"] = sum;

}
else
{
int chengji = chkCode * chkCode2;
Session["ValidateCode1"] = chengji;
}
for (int i = 0; i < 1; i++)
{
string num = shuzi[rnd.Next(shuzi.Length)].ToString();
int fnts = fontsize[rnd.Next(fontsize.Length)];
Font ft = new Font(num, fnts);
Color clr = color[rnd.Next(color.Length)];
g.DrawString(chkCode + fuhao1 + chkCode2 + "=?", ft, new SolidBrush(clr), (float)i * 10, (float)30);
}

for (int i = 0; i < 30; i++)
{
int x = rnd.Next(bmp.Width);
int y = rnd.Next(bmp.Height);
Color clr = color[rnd.Next(color.Length)];
bmp.SetPixel(x, y, clr);
}

Response.Buffer = true;
Response.BufferOutput = true;
Response.Cache.SetExpires(DateTime.Now.AddMilliseconds(-1));
Response.Cache.SetCacheability(HttpCacheability.NoCache);

Response.ExpiresAbsolute = System.DateTime.Now.AddMilliseconds(0);
Response.Expires = 0;
Response.CacheControl = "no-cache";
Response.AppendHeader("Pragma", "No-Cache");
MemoryStream ms = new MemoryStream();
try
{
bmp.Save(ms, ImageFormat.Png);
Response.ClearContent();
Response.ContentType = "image/Png";
Response.BinaryWrite(ms.ToArray());
}
finally
{
bmp.Dispose();
g.Dispose();
}
}

点击图片更换验证码

1
<img src="Numyzm.aspx" alt="验证码"  style="width:110px; height:55px;"onclick="this.src=this.src+'?'" />