廢話很少說直接上代碼。html
1 class Check_Code 2 { 3 /// <summary> 4 /// 生成隨機驗證碼數字+字母 5 /// </summary> 6 /// <param name="codelen">驗證碼長度</param> 7 /// <returns>返回驗證碼</returns> 8 public static string MakeCode(int codelen) 9 { 10 if (codelen < 1) 11 { 12 return string.Empty; 13 } 14 int number; 15 StringBuilder strCheckCode = new StringBuilder(); 16 Random random = new Random(); 17 for (int index = 0; index < codelen; index++) 18 { 19 number = random.Next(); 20 if (number % 2 == 0) 21 { 22 strCheckCode.Append((char)('0' + (char)(number % 10)));//生成隨機數字 23 } 24 else 25 { 26 strCheckCode.Append((char)('A' + (char)(number % 26)));//生成隨機字母 27 } 28 } 29 return strCheckCode.ToString(); 30 } 31 public static MemoryStream CheckCodeImage(string CheckCode) 32 { 33 if (string.IsNullOrEmpty(CheckCode)) 34 { 35 return null; 36 } 37 Bitmap image = new Bitmap((int)Math.Ceiling((CheckCode.Length * 12.5)), 22); 38 Graphics graphic = Graphics.FromImage(image);//建立一個驗證碼圖片 39 try 40 { 41 Random random = new Random(); 42 graphic.Clear(Color.White); 43 int x1 = 0, y1 = 0, x2 = 0, y2 = 0; 44 for (int index = 0; index < 25; index++) 45 { 46 x1 = random.Next(image.Width); 47 x2 = random.Next(image.Width); 48 y1 = random.Next(image.Height); 49 y2 = random.Next(image.Height); 50 graphic.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2); 51 } 52 Font font = new Font("Arial", 12, (FontStyle.Bold | FontStyle.Italic));//Font設置字體,字號,字形 53 //設置圖形漸變色的起始顏色與終止顏色,漸變角度 54 LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Red, Color.DarkRed, 1.2f, true); 55 graphic.DrawString(CheckCode, font, brush, 2, 2); 56 int X = 0; int Y = 0; 57 //繪製圖片的前景噪點 58 for (int i = 0; i < 100; i++) 59 { 60 X = random.Next(image.Width); 61 Y = random.Next(image.Height); 62 image.SetPixel(X, Y, Color.FromArgb(random.Next())); 63 } 64 //畫圖片的邊框線 65 graphic.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1); 66 //將圖片保存爲stream流返回 67 MemoryStream ms = new MemoryStream(); 68 image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif); 69 return ms; 70 } 71 finally 72 { 73 graphic.Dispose(); 74 image.Dispose(); 75 } 76 } 77 }
生成驗證碼圖片,須要先生成驗證碼,再將驗證碼處理爲圖片。dom
轉載引用黎木博客-https://www.cnblogs.com/running-mydream/p/4071528.html字體