-
Notifications
You must be signed in to change notification settings - Fork 0
/
ValidateImg.cs
65 lines (61 loc) · 2.37 KB
/
ValidateImg.cs
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
using System;
using System.Drawing;
namespace DotNet.Utilities
{
/// <summary>
/// 验证码 继承 System.Web.UI.Page ,Session["xk_validate_code"]
/// </summary>
public class ValidateImg : System.Web.UI.Page
{
private void Page_Load(object sender, EventArgs e)
{
char[] chars = "023456789".ToCharArray();
System.Random random = new Random();
string validateCode = string.Empty;
for (int i = 0; i < 4; i++)
{
char rc = chars[random.Next(0, chars.Length)];
if (validateCode.IndexOf(rc) > -1)
{
i--;
continue;
}
validateCode += rc;
}
Session["xk_validate_code"] = validateCode;
CreateImage(validateCode);
}
/// <summary>
/// 创建图片
/// </summary>
/// <param name="checkCode"></param>
private void CreateImage(string checkCode)
{
int iwidth = (int)(checkCode.Length * 11);
System.Drawing.Bitmap image = new System.Drawing.Bitmap(iwidth, 19);
Graphics g = Graphics.FromImage(image);
g.Clear(Color.White);
//定义颜色
Color[] c = { Color.Black, Color.Red, Color.DarkBlue, Color.Green, Color.Chocolate, Color.Brown, Color.DarkCyan, Color.Purple };
Random rand = new Random();
//输出不同字体和颜色的验证码字符
for (int i = 0; i < checkCode.Length; i++)
{
int cindex = rand.Next(7);
Font f = new System.Drawing.Font("Microsoft Sans Serif", 11);
Brush b = new System.Drawing.SolidBrush(c[cindex]);
g.DrawString(checkCode.Substring(i, 1), f, b, (i * 10) + 1, 0, StringFormat.GenericDefault);
}
//画一个边框
g.DrawRectangle(new Pen(Color.Black, 0), 0, 0, image.Width - 1, image.Height - 1);
//输出到浏览器
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();
}
}
}