Net Core 生成图形验证码

      在我第一次绘制图形验证码时是采用的ZKweb的绘制库,奉上代码参考

    

1 public byte[] GetVerifyCode(out string code) 2 { 3 code = string.Empty; 4 int codeW = 80; 5 int codeH = 30; 6 int fontSize = 16; 7 string chkCode = string.Empty; 8 Random rnd = new Random(); 9 //颜色列表,用于验证码、噪线、噪点 10 System.DrawingCore.Color[] color = { Color.Black, Color.Red, Color.Blue, Color.Green, Color.Orange, Color.Brown, Color.Brown, Color.DarkBlue }; 11 //字体列表,用于验证码 12 string[] font = { "Times New Roman" }; 13 //验证码的字符集,去掉了一些容易混淆的字符 14 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' }; 15 //生成验证码字符串 16 for (int i = 0; i < 4; i++) 17 { 18 chkCode += character[rnd.Next(character.Length)]; 19 } 20 code = chkCode; 21 22 //创建画布 23 Bitmap bmp = new Bitmap(codeW, codeH); 24 Graphics g = Graphics.FromImage(bmp); 25 g.Clear(Color.White); 26 //画噪线 27 for (int i = 0; i < 1; i++) 28 { 29 int x1 = rnd.Next(codeW); 30 int y1 = rnd.Next(codeH); 31 int x2 = rnd.Next(codeW); 32 int y2 = rnd.Next(codeH); 33 Color clr = color[rnd.Next(color.Length)]; 34 g.DrawLine(new Pen(clr), x1, y1, x2, y2); 35 } 36 //画验证码字符串 37 for (int i = 0; i < chkCode.Length; i++) 38 { 39 string fnt = font[rnd.Next(font.Length)]; 40 Font ft = new Font(fnt, fontSize); 41 Color clr = color[rnd.Next(color.Length)]; 42 g.DrawString(chkCode[i].ToString(), ft, new SolidBrush(clr), (float)i * 18, (float)0); 43 } 44 //将验证码图片写入内存流,并将其以 "image/Png" 格式输出 45 MemoryStream ms = new MemoryStream(); 46 try 47 { 48 bmp.Save(ms, ImageFormat.Png); 49 return ms.ToArray(); 50 } 51 catch (Exception) 52 { 53 return null; 54 } 55 finally 56 { 57 g.Dispose(); 58 bmp.Dispose(); 59 } 60 }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wpyyss.html