首页 > 代码库 > ASP.NET中画图形验证码

ASP.NET中画图形验证码

 1             context.Response.ContentType = "image/jpeg";
 2             //生成随机的中文验证码
 3             string yzm = "人口手大小多少上中下男女天地会反清复明杨中科小宝双儿命名空间语现在明天来多个的我山东河北南固安北京南昌东海西安是沙河高教园学"
 4                 + "木禾上下土个八入大天人火文六七儿九无口日中了子门月不开四五目耳头米见白田电也长山出飞马鸟云公车牛羊小少巾牙尺毛又心手水广升足"
 5                 + "走方半巴业本平书自已东西回片皮生里果几用鱼今正雨两瓜衣来年左右万百丁齐冬说友话春朋高你绿们花红草爷亲节的岁行古处声知多忙洗真认父扫"
 6                 + "母爸写全完关家看笑着兴画会妈合奶放午收女气太早去亮和李语秀千香听远唱定连向以更后意主总先起干明赶净同专工才级队蚂蚁前房空网诗黄林闭"
 7                 + "童立是我朵叶美机她过他时送让吗往吧得虫很河借姐呢呀哪谁凉怕量跟最园脸因阳为光可法石找办许别那到都吓叫再做象点像照沙海桥军竹苗井面乡"
 8                 + "忘想念王这从进边道贝男原爱虾跑吹乐地老快师短淡对热冷情拉活把种给吃练学习非苦常问伴间共伙汽分要没孩位选北湖南秋江只帮星请雪就球跳玩"
 9                 + "桃树刚兰座各带坐急名发成动晚新有么在变什条";
10             Random r = new Random();
11             string validCode = "";
12             for (int i = 0; i < 4; i++)
13             {
14                 int number = r.Next(0, yzm.Length);
15                 validCode += yzm[number];
16             }
17 
18             //画图
19             using(Bitmap b = new Bitmap(150, 30))
20             {
21                 using (Graphics g = Graphics.FromImage(b))
22                 using(Font f = new Font("宋体", 20))
23                 {
24                     g.Clear(Color.Yellow);//清除整个绘画面并填充指定背景色
25                     g.DrawString(validCode, f, Brushes.Red, new PointF(0, 0));//开始绘制
26                     //前景点
27                     for (int i = 0; i < 100; i++)
28                     {
29                         int x = r.Next(0, 150);
30                         int y = r.Next(0, 30);
31                         b.SetPixel(x, y, Color.Red);
32                     }
33                     //后景线
34                     for (int i = 0; i < 100; i++)
35                     {
36                         int x = r.Next(0, 150);
37                         int y = r.Next(0, 30);
38                         g.DrawLine(Pens.Red, x, y, x + 1, y + 1);
39                     }
40                 }
41                 b.Save(context.Response.OutputStream, ImageFormat.Jpeg);//保存到输出流中
42             }

 

ASP.NET中画图形验证码