using System; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Text;
public class CaptchaHelper { public (string key, string base64) GenerateCaptcha() { string key = Guid.NewGuid().ToString("N"); // 生成一个唯一的Key string captchaText = GenerateRandomCode(4); // 生成一个4位随机验证码
Bitmap bitmap = new Bitmap(100, 30); Graphics graphic = Graphics.FromImage(bitmap);
try { var rnd = new Random(); // 设置验证码的字体、颜色等属性 Random random = new Random(); Font font = new Font("Arial", 15, FontStyle.Bold); Brush brush = new SolidBrush(Color.FromArgb(rnd.Next(0, 256), rnd.Next(0, 256), rnd.Next(0, 256), rnd.Next(0, 256))); PointF point = new PointF(5, 5);
private string GenerateRandomCode(int length) { const string randomCode = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; Random random = new Random(); StringBuilder sb = new StringBuilder();
for (int i = 0; i < length; i++) { sb.Append(randomCode[random.Next(randomCode.Length)]); }
return sb.ToString(); } }
控制器
[HttpGet] public async Task<IActionResult> Captcha() { (string key, string base64) =new CaptchaHelper().GenerateCaptcha(); return Ok(new { code, data = new { captchaKey = key, captchaBase64 = "data:image/png;base64,"+ base64 } }); }