【类】随机验证码
这是一个随机生成验证码的类,具体调用方法:
1、先实例化一个类对象: VerificationNumImgUtility vnu = new VerificationNumImgUtility() ;
2、将获得的验证图片赋给PictrueBox或其他用来显示图片的控件即可:
pictureBox1.ImageLocation = vnu.GenImageFile();
1 /// <summary>
2 /// 生成随机验证码类
3 /// </summary>
4 class VerificationNumImgUtility
5 {
6 #region 字段
7 private int sumCharsOfVerNum = 4;
8 private int imageWidth = 100;
9 private int imageHeight = 30;
10 private string imageName = "VerNum";
11 private Font fontVerNum = new Font("Consolas", 14, FontStyle.Bold, GraphicsUnit.Pixel);
12 #endregion
13
14 #region 变量
15 private SizeF[] charSizesOfVerNum;
16 private string verNum;
17 #endregion
18
19 #region 常量
20 private string[] charsToGenVerNum = { "0","1","2","3","4","5","6","7","8","9",
21 "A","B","C","D","E","F","G","H","I","J",
22 "K","L","M","N","O","P","Q","R","S","T",
23 "U","V","W","X","Y","Z","a","b","c","d",
24 "e","f","g","h","i","j","k","l","m","n",
25 "o","p","q","r","s","t","u","v","w","x",
26 "y","z"};
27 #endregion
28
29 #region 属性
30 /// <summary>
31 /// 验证码文件名称
32 /// </summary>
33 public string ImageName
34 {
35 get
36 {
37 return this.imageName;
38 }
39 set
40 {
41 this.imageName = string.IsNullOrEmpty(value) ? "VerNum" : value;
42 }
43 }
44
45 /// <summary>
46 /// 验证码的字符数
47 /// </summary>
48 public int SumCharsOfVerNum
49 {
50 get
51 {
52 return this.sumCharsOfVerNum;
53 }
54 set
55 {
56 this.sumCharsOfVerNum = value > 0 ? value : this.sumCharsOfVerNum;
57 }
58 }
59
60 /// <summary>
61 /// 图像宽度
62 /// </summary>
63 public int ImageWidth
64 {
65 get
66 {
67 return this.imageWidth;
68 }
69 set
70 {
71 this.imageWidth = value > 0 ? value : this.imageWidth;
72 }
73 }
74
75 /// <summary>
76 /// 图像高度
77 /// </summary>
78 public int ImageHeight
79 {
80 get
81 {
82 return this.imageHeight;
83 }
84 set
85 {
86 this.imageHeight = value > 0 ? value : this.imageHeight;
87 }
88 }
89
90
91 /// <summary>
92 /// 字符串的值
93 /// </summary>
94 public string VarString
95 {
96 get
97 {
98 return this.verNum;
99 }
100 set
101 {
102 verNum = value;
103 }
104 }
105 /// <summary>
106 /// 设置字体
107 /// </summary>
108 public Font FontVerNum
109 {
110 get
111 {
112 return this.fontVerNum;
113 }
114 set
115 {
116 this.fontVerNum = value;
117 }
118 }
119 #endregion
120
121 #region 构造函数
122 public VerificationNumImgUtility()
123 : this(4, 100, 30, "VerNum", "Consolas", 16)
124 { }
125
126 public VerificationNumImgUtility(string imageName)
127 : this(4, 100, 30, imageName, "Consolas", 16)
128 { }
129
130 public VerificationNumImgUtility(int imageWidth, int imageHeigh, string imageName)
131 : this(4, imageWidth, imageHeigh, imageName, "Consolas", 16)
132 { }
133
134 public VerificationNumImgUtility(int sumCharsOfVerNum, int imageWidth, int imageHeight, string imageName, string fontName, float fontSize)
135 {
136 this.sumCharsOfVerNum = sumCharsOfVerNum;
137 this.imageWidth = imageWidth;
138 this.imageHeight = imageHeight;
139 this.imageName = imageName;
140 this.fontVerNum = new Font(fontName, fontSize, FontStyle.Bold, GraphicsUnit.Pixel);
141 this.charSizesOfVerNum = new SizeF[sumCharsOfVerNum];
142 }
143 #endregion
144
145 /// <summary>
146 /// 产生随机验证码
147 /// </summary>
148 /// <returns>验证码数组</returns>
149 private string[] GenRandomChars()
150 {
151 Random r = new Random();
152 string[] genedCharsOfVerNum = new string[this.sumCharsOfVerNum];
153 verNum = "";
154 for (int i = 0; i < this.sumCharsOfVerNum; i++)
155 {
156 int index = r.Next(0, charsToGenVerNum.Length);
157 genedCharsOfVerNum[i] = charsToGenVerNum[index];
158
159 this.verNum = string.Concat(this.verNum, this.charsToGenVerNum[index]);
160 }
161
162 return genedCharsOfVerNum;
163 }
164
165 /// <summary>
166 /// 验证码每位的大小
167 /// </summary>
168 /// <param name="genedCharsOfVerNum">验证码数组</param>
169 /// <param name="g">当前图像类</param>
170 private void MeasureCharSizesOfVerNum(string[] genedCharsOfVerNum, Graphics g)
171 {
172 if (genedCharsOfVerNum == null)
173 {
174 return;
175 }
176
177 for (int i = 0; i < this.sumCharsOfVerNum; i++)
178 {
179 this.charSizesOfVerNum[i] = g.MeasureString(genedCharsOfVerNum[i], this.fontVerNum);
180 }
181 }
182
183 /// <summary>
184 /// 产生验证码的位置
185 /// </summary>
186 /// <returns></returns>
187 private Point[] GenRandomPostions()
188 {
189
190 Random r = new Random();
191 string genedY = string.Empty;
192 Point[] genedCharPostionsOfVerNum = new Point[4];
193
194 for (int i = 0; i < this.sumCharsOfVerNum; i++)
195 {
196 genedCharPostionsOfVerNum[i].X = Convert.ToInt32(charSizesOfVerNum[i].Width / 2 + (Convert.ToDouble(this.imageWidth) - charSizesOfVerNum[i].Width * 2) / (sumCharsOfVerNum * 2) * (2 * i + 1));
197
198
199 int maxY = this.imageHeight - Convert.ToInt32(charSizesOfVerNum[i].Height);
200 int y = r.Next(0, maxY);
201
202 //保证y坐标都不同
203 while (genedY.Contains(y.ToString()))
204 {
205 y = r.Next(0, maxY);
206 }
207
208 genedY = string.Concat(genedY, ",", y);
209
210 genedCharPostionsOfVerNum[i].Y = y;
211 }
212
213 return genedCharPostionsOfVerNum;
214 }
215
216 /// <summary>
217 /// 生成BMP文件
218 /// </summary>
219 /// <returns>验证码字符串</returns>
220 public string GenImageFile()
221 {
222 return GenImageFile(ImageFormat.Bmp);
223 }
224
225 /// <summary>
226 /// 生成文件,并打开
227 /// </summary>
228 /// <param name="f">文件类型</param>
229 /// <returns>验证码字符串</returns>
230 public string GenImageFile(ImageFormat f)
231 {
232 Bitmap bmpVerNum = GenBMPObject(this.sumCharsOfVerNum);
233 string path = Directory.GetCurrentDirectory() + "\\" + this.imageName + "." + f.ToString();
234
235 try
236 {
237 bmpVerNum.Save(path, f);
238 }
239 catch (Exception)
240 {
241 ShowMessage("Error saving image file!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
242 Environment.Exit(-1);
243 }
244 finally
245 {
246 bmpVerNum.Dispose();
247 }
248
249 //try
250 //{
251 // Process.Start(path);
252 //}
253 //catch (Exception)
254 //{
255 // ShowMessage("Error opening image file!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
256 // Environment.Exit(-1);
257 //}
258
259 return path;
260 }
261
262 /// <summary>
263 /// 生成BMP文件对象
264 /// </summary>
265 /// <param name="sumCharsOfVerNum"></param>
266 /// <returns>BMP文件对象</returns>
267 private Bitmap GenBMPObject(int sumCharsOfVerNum)
268 {
269 Bitmap bmpVerNum = null;
270 try
271 {
272 bmpVerNum = new Bitmap(this.imageWidth, this.imageHeight);
273 }
274 catch (SystemException)
275 {
276 ShowMessage("Error creating bitmap file!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
277 Environment.Exit(-1);
278 }
279
280 Graphics graphicVerNumImg = Graphics.FromImage(bmpVerNum);
281 graphicVerNumImg.SmoothingMode = SmoothingMode.HighQuality;
282 graphicVerNumImg.FillRectangle(new SolidBrush(Color.White), 0, 0, this.imageWidth, this.imageHeight);
283
284 string[] genedVerNums = GenRandomChars();
285 MeasureCharSizesOfVerNum(genedVerNums, graphicVerNumImg);
286 Point[] genedVerNumPositons = GenRandomPostions();
287
288 for (int i = 0; i < sumCharsOfVerNum; i++)
289 {
290 graphicVerNumImg.DrawString(genedVerNums[i], fontVerNum, new SolidBrush(Color.Tomato), genedVerNumPositons[i]);
291 }
292
293 graphicVerNumImg.Dispose();
294
295 return bmpVerNum;
296 }
297
298 /// <summary>
299 /// 来自CodeProject,使提示框置顶
300 /// </summary>
301 /// <param name="message"></param>
302 /// <param name="title"></param>
303 /// <param name="buttons"></param>
304 /// <param name="icon"></param>
305 /// <returns></returns>
306 private DialogResult ShowMessage(string message, string title, MessageBoxButtons buttons, MessageBoxIcon icon)
307 { // Create a host form that is a TopMost window which will be the parent of the MessageBox.
308 Form topmostForm = new Form();
309 // We do not want anyone to see this window so position it off the visible screen and make it as small as possible
310 topmostForm.Size = new System.Drawing.Size(1, 1);
311 topmostForm.StartPosition = FormStartPosition.Manual;
312 System.Drawing.Rectangle rect = SystemInformation.VirtualScreen;
313 topmostForm.Location = new System.Drawing.Point(rect.Bottom + 10, rect.Right + 10);
314 topmostForm.Show();
315 // Make this form the active form and make it TopMost
316 topmostForm.Focus();
317 topmostForm.BringToFront();
318 topmostForm.TopMost = true;
319 // Finally show the MessageBox with the form just created as its owner
320 DialogResult result = MessageBox.Show(topmostForm, message, title, buttons, icon);
321 topmostForm.Dispose(); // clean it up all the way
322
323 return result;
324 }
325 }
2 /// 生成随机验证码类
3 /// </summary>
4 class VerificationNumImgUtility
5 {
6 #region 字段
7 private int sumCharsOfVerNum = 4;
8 private int imageWidth = 100;
9 private int imageHeight = 30;
10 private string imageName = "VerNum";
11 private Font fontVerNum = new Font("Consolas", 14, FontStyle.Bold, GraphicsUnit.Pixel);
12 #endregion
13
14 #region 变量
15 private SizeF[] charSizesOfVerNum;
16 private string verNum;
17 #endregion
18
19 #region 常量
20 private string[] charsToGenVerNum = { "0","1","2","3","4","5","6","7","8","9",
21 "A","B","C","D","E","F","G","H","I","J",
22 "K","L","M","N","O","P","Q","R","S","T",
23 "U","V","W","X","Y","Z","a","b","c","d",
24 "e","f","g","h","i","j","k","l","m","n",
25 "o","p","q","r","s","t","u","v","w","x",
26 "y","z"};
27 #endregion
28
29 #region 属性
30 /// <summary>
31 /// 验证码文件名称
32 /// </summary>
33 public string ImageName
34 {
35 get
36 {
37 return this.imageName;
38 }
39 set
40 {
41 this.imageName = string.IsNullOrEmpty(value) ? "VerNum" : value;
42 }
43 }
44
45 /// <summary>
46 /// 验证码的字符数
47 /// </summary>
48 public int SumCharsOfVerNum
49 {
50 get
51 {
52 return this.sumCharsOfVerNum;
53 }
54 set
55 {
56 this.sumCharsOfVerNum = value > 0 ? value : this.sumCharsOfVerNum;
57 }
58 }
59
60 /// <summary>
61 /// 图像宽度
62 /// </summary>
63 public int ImageWidth
64 {
65 get
66 {
67 return this.imageWidth;
68 }
69 set
70 {
71 this.imageWidth = value > 0 ? value : this.imageWidth;
72 }
73 }
74
75 /// <summary>
76 /// 图像高度
77 /// </summary>
78 public int ImageHeight
79 {
80 get
81 {
82 return this.imageHeight;
83 }
84 set
85 {
86 this.imageHeight = value > 0 ? value : this.imageHeight;
87 }
88 }
89
90
91 /// <summary>
92 /// 字符串的值
93 /// </summary>
94 public string VarString
95 {
96 get
97 {
98 return this.verNum;
99 }
100 set
101 {
102 verNum = value;
103 }
104 }
105 /// <summary>
106 /// 设置字体
107 /// </summary>
108 public Font FontVerNum
109 {
110 get
111 {
112 return this.fontVerNum;
113 }
114 set
115 {
116 this.fontVerNum = value;
117 }
118 }
119 #endregion
120
121 #region 构造函数
122 public VerificationNumImgUtility()
123 : this(4, 100, 30, "VerNum", "Consolas", 16)
124 { }
125
126 public VerificationNumImgUtility(string imageName)
127 : this(4, 100, 30, imageName, "Consolas", 16)
128 { }
129
130 public VerificationNumImgUtility(int imageWidth, int imageHeigh, string imageName)
131 : this(4, imageWidth, imageHeigh, imageName, "Consolas", 16)
132 { }
133
134 public VerificationNumImgUtility(int sumCharsOfVerNum, int imageWidth, int imageHeight, string imageName, string fontName, float fontSize)
135 {
136 this.sumCharsOfVerNum = sumCharsOfVerNum;
137 this.imageWidth = imageWidth;
138 this.imageHeight = imageHeight;
139 this.imageName = imageName;
140 this.fontVerNum = new Font(fontName, fontSize, FontStyle.Bold, GraphicsUnit.Pixel);
141 this.charSizesOfVerNum = new SizeF[sumCharsOfVerNum];
142 }
143 #endregion
144
145 /// <summary>
146 /// 产生随机验证码
147 /// </summary>
148 /// <returns>验证码数组</returns>
149 private string[] GenRandomChars()
150 {
151 Random r = new Random();
152 string[] genedCharsOfVerNum = new string[this.sumCharsOfVerNum];
153 verNum = "";
154 for (int i = 0; i < this.sumCharsOfVerNum; i++)
155 {
156 int index = r.Next(0, charsToGenVerNum.Length);
157 genedCharsOfVerNum[i] = charsToGenVerNum[index];
158
159 this.verNum = string.Concat(this.verNum, this.charsToGenVerNum[index]);
160 }
161
162 return genedCharsOfVerNum;
163 }
164
165 /// <summary>
166 /// 验证码每位的大小
167 /// </summary>
168 /// <param name="genedCharsOfVerNum">验证码数组</param>
169 /// <param name="g">当前图像类</param>
170 private void MeasureCharSizesOfVerNum(string[] genedCharsOfVerNum, Graphics g)
171 {
172 if (genedCharsOfVerNum == null)
173 {
174 return;
175 }
176
177 for (int i = 0; i < this.sumCharsOfVerNum; i++)
178 {
179 this.charSizesOfVerNum[i] = g.MeasureString(genedCharsOfVerNum[i], this.fontVerNum);
180 }
181 }
182
183 /// <summary>
184 /// 产生验证码的位置
185 /// </summary>
186 /// <returns></returns>
187 private Point[] GenRandomPostions()
188 {
189
190 Random r = new Random();
191 string genedY = string.Empty;
192 Point[] genedCharPostionsOfVerNum = new Point[4];
193
194 for (int i = 0; i < this.sumCharsOfVerNum; i++)
195 {
196 genedCharPostionsOfVerNum[i].X = Convert.ToInt32(charSizesOfVerNum[i].Width / 2 + (Convert.ToDouble(this.imageWidth) - charSizesOfVerNum[i].Width * 2) / (sumCharsOfVerNum * 2) * (2 * i + 1));
197
198
199 int maxY = this.imageHeight - Convert.ToInt32(charSizesOfVerNum[i].Height);
200 int y = r.Next(0, maxY);
201
202 //保证y坐标都不同
203 while (genedY.Contains(y.ToString()))
204 {
205 y = r.Next(0, maxY);
206 }
207
208 genedY = string.Concat(genedY, ",", y);
209
210 genedCharPostionsOfVerNum[i].Y = y;
211 }
212
213 return genedCharPostionsOfVerNum;
214 }
215
216 /// <summary>
217 /// 生成BMP文件
218 /// </summary>
219 /// <returns>验证码字符串</returns>
220 public string GenImageFile()
221 {
222 return GenImageFile(ImageFormat.Bmp);
223 }
224
225 /// <summary>
226 /// 生成文件,并打开
227 /// </summary>
228 /// <param name="f">文件类型</param>
229 /// <returns>验证码字符串</returns>
230 public string GenImageFile(ImageFormat f)
231 {
232 Bitmap bmpVerNum = GenBMPObject(this.sumCharsOfVerNum);
233 string path = Directory.GetCurrentDirectory() + "\\" + this.imageName + "." + f.ToString();
234
235 try
236 {
237 bmpVerNum.Save(path, f);
238 }
239 catch (Exception)
240 {
241 ShowMessage("Error saving image file!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
242 Environment.Exit(-1);
243 }
244 finally
245 {
246 bmpVerNum.Dispose();
247 }
248
249 //try
250 //{
251 // Process.Start(path);
252 //}
253 //catch (Exception)
254 //{
255 // ShowMessage("Error opening image file!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
256 // Environment.Exit(-1);
257 //}
258
259 return path;
260 }
261
262 /// <summary>
263 /// 生成BMP文件对象
264 /// </summary>
265 /// <param name="sumCharsOfVerNum"></param>
266 /// <returns>BMP文件对象</returns>
267 private Bitmap GenBMPObject(int sumCharsOfVerNum)
268 {
269 Bitmap bmpVerNum = null;
270 try
271 {
272 bmpVerNum = new Bitmap(this.imageWidth, this.imageHeight);
273 }
274 catch (SystemException)
275 {
276 ShowMessage("Error creating bitmap file!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
277 Environment.Exit(-1);
278 }
279
280 Graphics graphicVerNumImg = Graphics.FromImage(bmpVerNum);
281 graphicVerNumImg.SmoothingMode = SmoothingMode.HighQuality;
282 graphicVerNumImg.FillRectangle(new SolidBrush(Color.White), 0, 0, this.imageWidth, this.imageHeight);
283
284 string[] genedVerNums = GenRandomChars();
285 MeasureCharSizesOfVerNum(genedVerNums, graphicVerNumImg);
286 Point[] genedVerNumPositons = GenRandomPostions();
287
288 for (int i = 0; i < sumCharsOfVerNum; i++)
289 {
290 graphicVerNumImg.DrawString(genedVerNums[i], fontVerNum, new SolidBrush(Color.Tomato), genedVerNumPositons[i]);
291 }
292
293 graphicVerNumImg.Dispose();
294
295 return bmpVerNum;
296 }
297
298 /// <summary>
299 /// 来自CodeProject,使提示框置顶
300 /// </summary>
301 /// <param name="message"></param>
302 /// <param name="title"></param>
303 /// <param name="buttons"></param>
304 /// <param name="icon"></param>
305 /// <returns></returns>
306 private DialogResult ShowMessage(string message, string title, MessageBoxButtons buttons, MessageBoxIcon icon)
307 { // Create a host form that is a TopMost window which will be the parent of the MessageBox.
308 Form topmostForm = new Form();
309 // We do not want anyone to see this window so position it off the visible screen and make it as small as possible
310 topmostForm.Size = new System.Drawing.Size(1, 1);
311 topmostForm.StartPosition = FormStartPosition.Manual;
312 System.Drawing.Rectangle rect = SystemInformation.VirtualScreen;
313 topmostForm.Location = new System.Drawing.Point(rect.Bottom + 10, rect.Right + 10);
314 topmostForm.Show();
315 // Make this form the active form and make it TopMost
316 topmostForm.Focus();
317 topmostForm.BringToFront();
318 topmostForm.TopMost = true;
319 // Finally show the MessageBox with the form just created as its owner
320 DialogResult result = MessageBox.Show(topmostForm, message, title, buttons, icon);
321 topmostForm.Dispose(); // clean it up all the way
322
323 return result;
324 }
325 }