驗證碼的作用嘛,基本就是用來防暴力破解,防惡意攻擊、注冊;
即便現在人工智能的高潮興起,OCR的廣泛應用;許多的驗證碼已經形同虛設,但是做一個專案,該有的基礎驗證我還是得有;你破你的,我防我的,大家開心就行,
一個簡單的驗證碼的生成方法;

實作功能:
隨機生成驗證碼并顯示到pictureBox
開發環境:
開發工具: Visual Studio 2013
.NET Framework版本:4.5
實作代碼:
private void GenerateCode(int codeLen = 6)
{
string code = "";
//生成亂數字
Random rand = new Random();
for (int i = 0; i < codeLen; i++)
{
code += rand.Next(0, 9).ToString();
}
/*這里將code保存下來做比對驗證*/
//生成驗證碼圖片并顯示到pictureBox1
byte[] bytes = GenerateImg(code);
MemoryStream ms = new MemoryStream(bytes);
Image image = System.Drawing.Image.FromStream(ms);
pictureBox1.Image = image;
}
/// <summary>
/// 生成驗證碼圖片
/// </summary>
/// <param name="code"></param>
/// <returns></returns>
public byte[] GenerateImg(string code)
{
Bitmap image = new Bitmap(code.Length * 10, 25);
Graphics g = Graphics.FromImage(image);
try
{
//清空圖片背景色
g.Clear(Color.White);
//增加背景干擾線
Random random = new Random();
for (int i = 0; i < 30; i++)
{
int x1 = random.Next(image.Width);
int x2 = random.Next(image.Width);
int y1 = random.Next(image.Height);
int y2 = random.Next(image.Height);
//顏色可自定義
g.DrawLine(new Pen(Color.FromArgb(186, 212, 231)), x1, y1, x2, y2);
}
//定義驗證碼字體
Font font = new Font("Arial", 10, (FontStyle.Bold | FontStyle.Italic | FontStyle.Strikeout));
//定義驗證碼的刷子,這里采用漸變的方式,顏色可自定義
LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.FromArgb(67, 93, 230), Color.FromArgb(70, 128, 228), 1.5f, true);
//增加干擾點
for (int i = 0; i < 100; i++)
{
int x = random.Next(image.Width);
int y = random.Next(image.Height);
//顏色可自定義
image.SetPixel(x, y, Color.FromArgb(random.Next()));
}
//將驗證碼寫入圖片
g.DrawString(code, font, brush, 5, 5);
//圖片邊框
g.DrawRectangle(new Pen(Color.FromArgb(93, 142, 228)), 0, 0, image.Width - 1, image.Height - 1);
//保存圖片資料
MemoryStream stream = new MemoryStream();
image.Save(stream, ImageFormat.Jpeg);
return stream.ToArray();
}
finally
{
g.Dispose();
image.Dispose();
}
}
//給pictureBox1添加一個點擊重繪的功能
private void pictureBox1_Click(object sender, EventArgs e)
{
GenerateCode();
}
//直接呼叫即可
GenerateCode();
實作效果:

若以上覺得比較簡單容易識別,可以自行再增加干擾點和干擾線,或者增加干擾的色度,以及采用字母加數字等的隨機生成,
由簡入繁,拿來即用
后續精彩,持續關注
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/340705.html
標籤:其他
下一篇:Postman鑒權
