C#生成驗證碼圖片的方法
更新時間:2018年10月04日 09:55:01 作者:薛定諤家的貓
這篇文章主要為大家詳細(xì)介紹了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#中使用BackgroundWorker的實現(xiàn)
本文主要介紹了c#中使用BackgroundWorker的實現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-06-06支持多類型數(shù)據(jù)庫的c#數(shù)據(jù)庫模型示例
本文為大家提供一個c#數(shù)據(jù)庫訪問模型,支持多類型數(shù)據(jù)庫,簡單抽取數(shù)據(jù)庫訪問函數(shù),大家參考使用吧2014-01-01