C#生成驗(yàn)證碼圖片的方法
更新時(shí)間:2018年10月04日 09:55:01 作者:薛定諤家的貓
這篇文章主要為大家詳細(xì)介紹了C#生成驗(yàn)證碼圖片的方法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
本文實(shí)例為大家分享了C#生成驗(yàn)證碼圖片的具體代碼,供大家參考,具體內(nèi)容如下
/// <summary>
/// 生成驗(yàn)證碼圖片
/// </summary>
/// <returns></returns>
public byte[] GetVerifyCode()
{
int codeW = 80;
int codeH = 40;
int fontSize = 18;
string chkCode = string.Empty;
//顏色列表,用于驗(yàn)證碼、噪線、噪點(diǎn)
Color[] color = { Color.Black, Color.Red, Color.Blue, Color.Green, Color.Orange, Color.Brown, Color.Brown, Color.DarkBlue };
//字體列表,用于驗(yàn)證碼
string[] font = { "Times New Roman" };
//驗(yàn)證碼的字符集,去掉了一些容易混淆的字符
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();
//生成驗(yàn)證碼字符串
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);
}
//畫驗(yàn)證碼字符串
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);
}
//將驗(yàn)證碼圖片寫入內(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)文章
Windows Form 分頁 具體實(shí)現(xiàn)
其實(shí)功能實(shí)現(xiàn)很簡單。我做的是一個(gè)通用的分頁控件。項(xiàng)目時(shí)間很緊,可能有點(diǎn)粗糙。歡迎大家斧正。不說了直接貼代碼吧2013-12-12
C#使用doggleReport生成pdf報(bào)表的方法
這篇文章主要介紹了C#使用doggleReport生成pdf報(bào)表的方法,結(jié)合實(shí)例形式分析了C# doggleReport安裝及使用具體操作技巧,需要的朋友可以參考下2017-06-06
c#中使用BackgroundWorker的實(shí)現(xiàn)
本文主要介紹了c#中使用BackgroundWorker的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-06-06
C#簡單多線程同步和優(yōu)先權(quán)用法實(shí)例
這篇文章主要介紹了C#簡單多線程同步和優(yōu)先權(quán)用法實(shí)例,對于C#線程的阻塞、同步、異步、互斥等概念做了較為深入的分析與實(shí)例講解,需要的朋友可以參考下2014-09-09
支持多類型數(shù)據(jù)庫的c#數(shù)據(jù)庫模型示例
本文為大家提供一個(gè)c#數(shù)據(jù)庫訪問模型,支持多類型數(shù)據(jù)庫,簡單抽取數(shù)據(jù)庫訪問函數(shù),大家參考使用吧2014-01-01

