验证码代码
jkj
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
1 using System;
2 using System.Data;
3 using System.Configuration;
4 using System.Collections;
5 using System.Web;
6 using System.Web.Security;
7 using System.Web.UI;
8 using System.Web.UI.WebControls;
9 using System.Web.UI.WebControls.WebParts;
10 using System.Web.UI.HtmlControls;
11 using System.IO;
12 using System.Drawing;
13 using System.Drawing.Design;
14 using System.Drawing.Imaging;
15 public partial class checkCode : System.Web.UI.Page
16 {
17 protected void Page_Load(object sender, EventArgs e)
18 {
19 int ImageHeight = 22;//定义图片的高度
20 int ImageWidth = 55;//定义图片的宽度
21 Font font = new Font("Arial", 12, FontStyle.Bold);//定义字体
22 Brush brush=new SolidBrush(Color.Black);//定义工具
23 Bitmap bitmap = new Bitmap(ImageWidth, ImageHeight);//定义画板
24 Graphics graphics = Graphics.FromImage(bitmap);//在定义的画板上绘图
25 graphics.Clear(ColorTranslator.FromHtml("#f0f0f0"));//填充背景颜色
26 RectangleF rect=new RectangleF (5,2,ImageWidth,ImageHeight);//定义个绘图形状
27 Pen pen1 = new Pen(Color.Blue);//定义钢笔 绘制干扰线
28 Pen pen2 = new Pen(Color.DarkGreen);//定义钢笔 绘制干扰线
29 Random rand= new Random() ;
30 for (int i = 0; i < 2; i++)//绘制两条横向干扰线
31 {
32 Point p1=new Point (0,rand.Next(ImageWidth));
33 Point p2=new Point (ImageWidth,rand.Next(ImageWidth));
34 graphics.DrawLine(pen1 ,p1,p2);
35
36 }
37
38 for (int i = 0; i < 2; i++)//绘制两条纵向干扰线
39 {
40 Point p1 = new Point(0, rand.Next(ImageHeight));
41 Point p2 = new Point(ImageHeight, rand.Next(ImageHeight));
42 graphics.DrawLine(pen2, p1, p2);
43
44 }
45 graphics.DrawString(CheckRandomCode(), font, brush, rect);//绘制验证码文字
46 bitmap.Save(Response.OutputStream, ImageFormat.Gif);//保存为gif格式的图片
47 graphics.Dispose();
48 bitmap.Dispose();
49
50 }
51 public string CheckRandomCode()
52 {
53 Random rom = new Random();
54 char[] allcheckRandom ={'0','1','2','3','4','5','6','7','8','9','A','B','C',
55 'D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W',
56 'X','Y','Z','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q',
57 'r','s','t','u','v','w','x','y','z'};
58 string Randomcode = "";
59 for (int i = 0; i < 4; i++)
60 {
61 Randomcode += allcheckRandom[rom.Next(allcheckRandom.Length)];
62 Session["verty"] = Randomcode;
63
64 }
65 return Randomcode;
66 }
67 }
68
69
可以在任何一个页面引用 比如在首页增加一个图片空间
只需要把ImageUrl指向生成验证码的的网页地址 就ok了
比如假设这个验证码的网页是 yzma.aspx 在index.aspx的图片控件<asp:Image ID="lbValid" runat="server" ImageUrl="yzma.aspx" />