以下是一个生成图形验证码并输出 Base64 的示例代码:

using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Web.Http;

namespace MyWebApi.Controllers
{
    public class CaptchaController : ApiController
    {
        [HttpGet]
        [Route("api/captcha")]
        public IHttpActionResult GetCaptcha()
        {
            // 生成随机验证码字符串
            string code = GenerateRandomCode();

            // 创建验证码图片
            Bitmap image = GenerateCaptchaImage(code);

            // 将图片转换为base64字符串
            string base64 = ConvertImageToBase64(image);

            // 返回base64字符串
            return Ok(base64);
        }

        private string GenerateRandomCode()
        {
            // TODO: 生成随机验证码字符串的代码
            return "ABCD";
        }

        private Bitmap GenerateCaptchaImage(string code)
        {
            // 创建图片对象
            Bitmap image = new Bitmap(100, 30);

            // 创建画笔对象
            Graphics graphics = Graphics.FromImage(image);

            // 填充背景色
            graphics.Clear(Color.White);

            // 绘制验证码字符串
            Font font = new Font("Arial", 16);
            Brush brush = new SolidBrush(Color.Black);
            graphics.DrawString(code, font, brush, new PointF(10, 5));

            // 绘制干扰线
            Random random = new Random();
            for (int i = 0; i < 10; i++)
            {
                int x1 = random.Next(0, image.Width);
                int y1 = random.Next(0, image.Height);
                int x2 = random.Next(0, image.Width);
                int y2 = random.Next(0, image.Height);
                graphics.DrawLine(Pens.Gray, x1, y1, x2, y2);
            }

            // 绘制噪点
            for (int i = 0; i < 100; i++)
            {
                int x = random.Next(0, image.Width);
                int y = random.Next(0, image.Height);
                image.SetPixel(x, y, Color.Black);
            }

            // 返回图片对象
            return image;
        }

        private string ConvertImageToBase64(Bitmap image)
        {
            // 将图片转换为内存流
            MemoryStream stream = new MemoryStream();
            image.Save(stream, ImageFormat.Png);

            // 将内存流转换为字节数组
            byte[] bytes = stream.ToArray();

            // 将字节数组转换为base64字符串
            string base64 = Convert.ToBase64String(bytes);

            // 返回base64字符串
            return base64;
        }
    }
}

使用浏览器访问'http://localhost:port/api/captcha',即可获取到一个图形验证码的 Base64 字符串。

NET 6 Web API 项目生成图形验证码并输出 Base64 示例

原文地址: https://www.cveoy.top/t/topic/lwNX 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录