C#生成驗證碼圖片的方法
更新時間:2018年10月04日 09:55:01 作者:薛定諤家的貓
這篇文章主要為大家詳細介紹了C#生成驗證碼圖片的方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下
本文實例為大家分享了C#生成驗證碼圖片的具體代碼,供大家參考,具體內(nèi)容如下
/// <summary>
/// 生成驗證碼圖片
/// </summary>
/// <returns></returns>
public byte[] GetVerifyCode()
{
int codeW = 80;
int codeH = 40;
int fontSize = 18;
string chkCode = string.Empty;
//顏色列表,用于驗證碼、噪線、噪點
Color[] color = { Color.Black, Color.Red, Color.Blue, Color.Green, Color.Orange, Color.Brown, Color.Brown, Color.DarkBlue };
//字體列表,用于驗證碼
string[] font = { "Times New Roman" };
//驗證碼的字符集,去掉了一些容易混淆的字符
char[] character = { '2', '3', '4', '5', '6', '8', '9', 'a', 'b', 'd', 'e', 'f', 'h', 'k', 'm', 'n', 'r', 'x', 'y', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'R', 'S', 'T', 'W', 'X', 'Y' };
Random rnd = new Random();
//生成驗證碼字符串
for (int i = 0; i < 4; i++)
{
chkCode += character[rnd.Next(character.Length)];
}
//創(chuàng)建畫布
Bitmap bmp = new Bitmap(codeW, codeH);
Graphics g = Graphics.FromImage(bmp);
g.Clear(Color.White);
//畫噪線
for (int i = 0; i < 1; i++)
{
int x1 = rnd.Next(codeW);
int y1 = rnd.Next(codeH);
int x2 = rnd.Next(codeW);
int y2 = rnd.Next(codeH);
Color clr = color[rnd.Next(color.Length)];
g.DrawLine(new Pen(clr), x1, y1, x2, y2);
}
//畫驗證碼字符串
for (int i = 0; i < chkCode.Length; i++)
{
string fnt = font[rnd.Next(font.Length)];
Font ft = new Font(fnt, fontSize);
Color clr = color[rnd.Next(color.Length)];
g.DrawString(chkCode[i].ToString(), ft, new SolidBrush(clr), (float)i * 18, (float)0);
}
//將驗證碼圖片寫入內(nèi)存流,并將其以 "image/Png" 格式輸出
MemoryStream ms = new MemoryStream();
try
{
bmp.Save(ms, ImageFormat.Png);
return ms.ToArray();
}
catch (Exception)
{
return null;
}
finally
{
g.Dispose();
bmp.Dispose();
}
}
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
C#.net實現(xiàn)在Winform中從internet下載文件的方法
這篇文章主要介紹了C#.net實現(xiàn)在Winform中從internet下載文件的方法,實例分析了基于Winform實現(xiàn)文件下載的相關(guān)技巧,需要的朋友可以參考下2015-07-07
C# 指針內(nèi)存控制Marshal內(nèi)存數(shù)據(jù)存儲原理分析
這篇文章主要介紹了C# 指針 內(nèi)存控制 Marshal 內(nèi)存數(shù)據(jù)存儲原理分析,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-02-02
DevExpress中GridControl列轉(zhuǎn)義的實現(xiàn)方法
這篇文章主要介紹了DevExpress中GridControl列轉(zhuǎn)義的實現(xiàn)方法,在項目開發(fā)中有一定的實用價值,需要的朋友可以參考下2014-08-08
通過容器擴展屬性IExtenderProvider實現(xiàn)WinForm通用數(shù)據(jù)驗證組件
這篇文章介紹了通過容器擴展屬性IExtenderProvider實現(xiàn)WinForm通用數(shù)據(jù)驗證組件的方法,文中通過示例代碼介紹的非常詳細。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-12-12

