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
| using system;
using system.data;
using system.configuration;
using system.collections;
using system.web;
using system.web.security;
using system.web.ui;
using system.web.ui.webcontrols;
using system.web.ui.webcontrols.webparts;
using system.web.ui.htmlcontrols;
using system.drawing;</textarea>
public partial class checkcode : system.web.ui.page
{
//验证码由生成彩色验证码和zhongfeng, http://blog.csdn.net/sw515 的验证码综合而成.
//感谢他们的劳动.
protected void page_load(object sender, eventargs e)
{
createimage(generatecheckcode());
}
private string generatecheckcode()
{
//生成checkcode
int number;
char code;
string checkcode = string.empty;
system.random random = new random();
for (int i = 0; i < 5; i++)
{
number = random.next();
if (number % 2 == 0)
code = (char)(‘‘0‘‘ + (char)(number % 10));
else
code = (char)(‘‘a‘‘ + (char)(number % 26));
checkcode += code.tostring();
}
//response.cookies.add(new httpcookie(“checkcode”, checkcode));
session.add(“checkcode”, checkcode);
return checkcode;
}
private void createimage(string checkcode)
{
if (checkcode == null || checkcode.trim() == string.empty)
return;
int iwidth = (int)(checkcode.length * 15);
system.drawing.bitmap image = new system.drawing.bitmap(iwidth, 25);
graphics g = graphics.fromimage(image);
g.clear(color.white);
//定义颜色
color[] c = { color.black, color.red, color.darkblue, color.green, color.orange, color.brown, color.darkcyan, color.purple };
//定义字体
string[] font = {“verdana”,”microsoft sans serif”,”comic sans ms”,”arial”,”宋体”};
random rand = new random();
//随机输出噪点
for (int i = 0; i < 100; i++)
{
int x = rand.next(image.width);
int y = rand.next(image.height);
g.drawrectangle(new pen(color.lightgray, 0), x, y, 1, 1);
}
//输出不同字体和颜色的验证码字符
for (int i = 0; i < checkcode.length; i++)
{
int cindex = rand.next(7);
int findex = rand.next(5);
font f = new system.drawing.font(font[findex], 10, system.drawing.fontstyle.bold);
brush b = new system.drawing.solidbrush(c[cindex]);
int ii = 4;
if ((i + 1) % 2 == 0)
{
ii = 2;
}
g.drawstring(checkcode.substring(i, 1), f, b, 3 + (i * 12), ii);
}
//画一个边框
g.drawrectangle(new pen(color.black, 0), 0, 0, image.width – 1, image.height – 7);
//输出到浏览器
system.io.memorystream ms = new system.io.memorystream();
image.save(ms, system.drawing.imaging.imageformat.jpeg);
response.clearcontent();
response.contenttype = “image/jpeg”;
response.binarywrite(ms.toarray());
g.dispose();
image.dispose();
}
}
|