1. 程式人生 > 其它 >C#返回驗證碼圖片記憶體流字串

C#返回驗證碼圖片記憶體流字串

1.上程式碼:

方法:

        /// <summary>
        /// 生成隨機驗證碼數字+字母
        /// </summary>
        /// <param name="codelen">驗證碼長度</param>
        /// <returns>返回驗證碼</returns>
        public static string MakeCode(int codelen)
        {
            if (codelen < 1)
            {
                
return string.Empty; } int number; StringBuilder strCheckCode = new StringBuilder(); Random random = new Random(); for (int index = 0; index < codelen; index++) { number = random.Next(); if (number % 2
== 0) { strCheckCode.Append((char)('0' + (char)(number % 10)));//生成隨機數字 } else { strCheckCode.Append((char)('A' + (char)(number % 26)));//生成隨機字母 } } return strCheckCode.ToString(); }
/// <summary> /// 根據驗證碼返回驗證碼圖片 /// </summary> /// <param name="CheckCode">驗證碼</param> /// <returns></returns> public string CheckCodeImage(string CheckCode) { if (string.IsNullOrEmpty(CheckCode)) { return null; } Bitmap image = new Bitmap((int)Math.Ceiling((CheckCode.Length * 12.5)), 22); Graphics graphic = Graphics.FromImage(image);//建立一個驗證碼圖片 try { Random random = new Random(); graphic.Clear(Color.White); int x1 = 0, y1 = 0, x2 = 0, y2 = 0; for (int index = 0; index < 25; index++) { x1 = random.Next(image.Width); x2 = random.Next(image.Width); y1 = random.Next(image.Height); y2 = random.Next(image.Height); graphic.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2); } Font font = new Font("Arial", 12, (FontStyle.Bold | FontStyle.Italic));//Font設定字型,字號,字形 //設定圖形漸變色的起始顏色與終止顏色,漸變角度 LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Red, Color.DarkRed, 1.2f, true); graphic.DrawString(CheckCode, font, brush, 2, 2); int X = 0; int Y = 0; //繪製圖片的前景噪點 for (int i = 0; i < 100; i++) { X = random.Next(image.Width); Y = random.Next(image.Height); image.SetPixel(X, Y, Color.FromArgb(random.Next())); } //畫圖片的邊框線 graphic.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1); //將圖片儲存為stream流返回 MemoryStream ms = new MemoryStream(); image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif); byte[] arr = new byte[ms.Length]; ms.Position = 0; ms.Read(arr, 0,(int)ms.Length); ms.Close(); return Convert.ToBase64String(arr); } finally { graphic.Dispose(); image.Dispose(); } }

前端使用:

<img src='data:image/gif;base64, 加上返回的字串/>

 

效果:

 

 

 

感謝:https://blog.csdn.net/weixin_42524279/article/details/87879624

https://www.cnblogs.com/dobiprogrammer/p/9722412.html