winfrom 底層類 驗證碼,winfrom底層
:
底層類:
/// <summary>
/// 產生驗證碼
/// </summary>
/// <param name="len">驗證碼長度</param>
/// <returns></returns>
private static string CreateRandomCode(int len) {
System.Random rand = new Random();
string randomCode = "";//隨機碼
char[] Allchar = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'T', 'Q', 'W', 'X', 'Y', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j', 'k', 'm', 'n', 'p', 'q', 't', 'w', 'x', 'y', 'z' };
for (int i = 0; i < len; i++) {
//產生一個小於Allchar.Length的隨機數
int a = rand.Next(Allchar.Length);
randomCode += Allchar[a].ToString();
}
//驗證碼
return randomCode;
}
/// <summary>
/// 產生驗證碼,填充到PictureBox中
/// </summary>
/// <param name="len">驗證碼長度</param>
/// <param name="pic">PictureBox名稱</param>
/// <param name="revolve">旋轉度數</param>
/// <param name="picHeight">圖片高度</param>
/// <param name="picWidth">圖片寬度</param>
/// <param name="charDistance">驗證碼中各個字元間距</param>
/// <param name="fontSize">驗證碼字元的大小</param>
public static string CreatePic(int len, PictureBox pic, int revolve, int picHeight, int picWidth, int charDistance, float fontSizes) {
//擷取驗證碼
string strCode = CreateRandomCode(len);
//建立背景圖片
Bitmap map = new Bitmap(picWidth, picHeight);
Graphics grap = Graphics.FromImage(map);
//清除畫面,填充背景色為AliceBlue
grap.Clear(Color.AliceBlue);
//畫一個矩形邊框
grap.DrawRectangle(new Pen(Color.Black, 0), 0, 0, map.Width - 1, map.Height - 1);
//模式
grap.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
//畫噪點
System.Random rand = new Random();
for (int i = 0; i < 50; i++) {
int x = rand.Next(0, map.Width - 1);
int y = rand.Next(0, map.Height - 1);
grap.DrawRectangle(new Pen(Color.Gray, 0), x, y, 1, 1);
}
//把字串拆成單個字元
char[] chars = strCode.ToCharArray();
//文字置中
StringFormat format = new StringFormat(StringFormatFlags.NoClip);
format.Alignment = StringAlignment.Center;
format.LineAlignment = StringAlignment.Center;
//定義顏色
Color[] colors = { Color.Red, Color.Black, Color.Blue, Color.Green, Color.Orange, Color.DarkCyan, Color.Purple };
//定義字型
string[] fonts = { "Arial", "Verdana", "Georgia", "Cambria Math", "華文中宋" };
for (int j = 0; j < len; j++) {
//顏色,字型的隨機數,隨機數作為下標
int cindex = rand.Next(colors.Length);
int findex = rand.Next(fonts.Length);
//字元顏色
Brush b = new System.Drawing.SolidBrush(colors[cindex]);
//字型樣式、大小
System.Drawing.Font f = new System.Drawing.Font(fonts[findex], fontSizes, FontStyle.Bold);
//定義一個點
System.Drawing.Point p = new System.Drawing.Point(16, 20);
//轉動的角度數
float angle = rand.Next(-revolve, revolve);
//移動游標到指定位置
grap.TranslateTransform(p.X, p.Y);
//轉動angle度
grap.RotateTransform(angle);
//賦值
grap.DrawString(chars[j].ToString(), f, b, 1, 1, format);
//轉動回去
grap.RotateTransform(-angle);
//移動游標到指定位置
grap.TranslateTransform(charDistance, -p.Y);
}
pic.Image = map;
pic.SizeMode = PictureBoxSizeMode.StretchImage;
return strCode;
}
前台調用:
說明:
(1)表單要有一個PictureBox控制項
(2)DataAccess 是底層類名稱
DataAccess.CreatePic(4, pic, 50, 40, 100, 3, 20);