.net core生成验证码图片

Posted 棉晗榜

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了.net core生成验证码图片相关的知识,希望对你有一定的参考价值。

NuGet安装包:
System.Drawing.Common

System.Runtime.Caching

画图支持:System.Drawing.Common
缓存支持:System.Runtime.Caching

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Drawing; 

/// <summary>
/// 获取当前登录验证码图片地址
/// </summary>
/// <returns></returns>
/// <remarks>
/// 创建时间:2021-9-14 17:47:17
/// </remarks>
public string GetVerificationCodeImgURL()
{
    Random random2 = new Random();
    int num = random2.Next(1000, 9999);

    //生成的验证码
    string code = num.ToString();
    System.Runtime.Caching.MemoryCache.Default.Set("login.verification.code", code, DateTime.Now.AddSeconds(600));

    //随机数生成验证码图片
    int widthSpan = 4;
    Bitmap image = new Bitmap((int)Math.Ceiling(code.Length * 28.0) + widthSpan, 40);
    Graphics g = Graphics.FromImage(image);
    try
    {
        //生成随机生成器
        Random random = new Random();
        //清空图片背景色
        g.Clear(Color.White);
        //画图片的干扰线
        for (int i = 0; i < 25; i++)
        {
            int x1 = random.Next(image.Width);
            int x2 = random.Next(image.Width);
            int y1 = random.Next(image.Height);
            int y2 = random.Next(image.Height);
            g.DrawLine(new Pen(Color.DarkBlue), x1, y1, x2, y2);
        }
        Font font = new Font("Arial", 30, (FontStyle.Bold | FontStyle.Italic));
        LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height),
        Color.Blue, Color.DarkRed, 1.2f, true);
        g.DrawString(code, font, brush, widthSpan, (image.Height - font.Height) / 2);
        //画图片的前景干扰点
        for (int i = 0; i < 100; i++)
        {
            int x = random.Next(image.Width);
            int y = random.Next(image.Height);
            image.SetPixel(x, y, Color.FromArgb(random.Next()));
        }

        string folder = AppDomain.CurrentDomain.BaseDirectory + "VerificationCodeImg\\\\";
        if (!System.IO.Directory.Exists(folder))
        {
            System.IO.Directory.CreateDirectory(folder);
        }
        string filePath = folder + DateTime.Now.Ticks + ".jpg";
        image.Save(filePath, ImageFormat.Jpeg);
        g.Dispose();
        image.Dispose();
        return filePath;
    }
    catch (Exception)
    {
    }
    return "";
}

以上是关于.net core生成验证码图片的主要内容,如果未能解决你的问题,请参考以下文章

.NET Core 中生成验证码

C#工具:ASP.NET MVC生成图片验证码

验证码识别与生成类API调用的代码示例合集:六位图片验证码生成四位图片验证码生成简单验证码识别等

015 图像验证码

建议收藏备用:.net core使用QRCoder生成普通二维码和带Logo的二维码详细使用教程,源码已更新至开源模板

PHP GD 生成图片验证码+session获取储存验证码