.Net WebAPI 生成圖形驗證碼

龙卷风吹毁停车场發表於2024-06-26

1.安裝nuget SkiaSharp
2.建立 VerifyCodeHelper幫助類

using SkiaSharp;

namespace WebApplication3
{
    public class VerifyCodeHelper
    {
        /// <summary>
        /// 獲取影像數字驗證碼
        /// </summary>
        /// <param name="text">驗證碼內容,如4為數字</param>
        /// <returns></returns>
        public static byte[] GetVerifyCode(string text)
        {

            int width = 74;
            int height = 36;

            Random random = new();
            //建立bitmap點陣圖
            using SKBitmap image = new(width, height, SKColorType.Bgra8888, SKAlphaType.Premul);
            //建立畫筆
            using SKCanvas canvas = new(image);
            //填充背景顏色為白色
            canvas.DrawColor(SKColors.White);
            //顏色列表
            SKColor[] colors = { SKColors.Black, SKColors.Red, SKColors.Blue, SKColors.Green, SKColors.Orange, SKColors.Brown, SKColors.DarkBlue };
            //畫圖片的背景噪音線
            for (int i = 0; i < 20; i++)
            {
                using SKPaint drawStyle = new();
                drawStyle.Color = colors[random.Next(colors.Length)];
                canvas.DrawLine(random.Next(0, width), random.Next(0, height), random.Next(0, width), random.Next(0, height), drawStyle);
            }
            //將文字寫到畫布上
            using (SKPaint drawStyle = new())
            {
                drawStyle.TextSize = height;
                drawStyle.StrokeWidth = 1;
                float emHeight = height - (float)height * (float)0.14;
                float emWidth = ((float)width / text.Length) - ((float)width * (float)0.13) + 5;
                for (int i = 0; i < text.Length; i++)
                {
                    drawStyle.Color = colors[random.Next(colors.Length)];

                    var jg = (width - (emWidth * text.Length)) / text.Length - 1;
                    //畫在畫板上
                    canvas.DrawText(text[i].ToString(), emWidth * i + jg, emHeight, drawStyle);
                }

            }

            //畫圖片的前景噪音點
            for (int i = 0; i < 100; i++)
            {
                image.SetPixel(random.Next(0, width), random.Next(0, height), colors[random.Next(colors.Length)]);
            }

            using var img = SKImage.FromBitmap(image);
            using SKData p = img.Encode(SKEncodedImageFormat.Png, 100);
            return p.ToArray();
        }

    }

}

使用 :

[HttpGet]
public IActionResult ObtainImageVerificationCode()
{
    //var images = ImageVerificationCode.CreateVerifyCode(4, VerifyCodeType.NUM);
    Random rad = new Random(); //例項化隨機數產生器rad;
    int value = rad.Next(1000, 10000);
    var arr = VerifyCodeHelper.GetVerifyCode(value.ToString());
    return Ok(new { Id = 1, Image = "data:image/png;base64," + Convert.ToBase64String(arr) });
}

原文地址: https://blog.csdn.net/weixin_46193339/article/details/128074161

相關文章