后端生成验证码
环境
一、前端请求
export async function getCaptcha() {
const res = await request.get('/Commons/getCaptcha');
if (res.data.code == 200) {
return res.data.data;
}
return Promise.reject(new Error(res.data.message));
}
二、后端实现
请求方法控制器
[HttpGet]
public JObject getCaptcha()
{
JObject json = new JObject();
string code = "";
var imageBase64 = GenerateCode(out code); // 生成验证码
CaptchaObj captchaObj = new CaptchaObj();
captchaObj.base64 = "data:image/png;base64,"+imageBase64.ToString();
captchaObj.text = code;
string result = JsonConvert.SerializeObject(captchaObj);
var obj = JObject.Parse(result);
json.Add("code", "200");
json.Add("data", obj);
json.Add("message", "操作成功!");
return json;
}
二、生成验证码
/// <summary>
/// 生成验证码
/// </summary>
/// <param name="codeLen">验证码长度</param>
/// <returns></returns>
private string GenerateCode(out string code,int codeLen = 5)
{
string letters = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
code = string.Empty;
Random random = new Random();
//生成四位验证码
for (int i = 0; i < 5; i++)
{
code+= letters[random.Next(0, letters.Length)];
}
/*这里将code保存下来做比对验证*/
//生成验证码图片并显示到pictureBox1
byte[] bytes = GenerateImg(code); // 生成图片字节
MemoryStream ms = new MemoryStream(bytes);
return Convert.ToBase64String(bytes);
//pictureBox1.Image = image;
}
三、生成验证码图片
public byte[] GenerateImg(string code)
{
Bitmap image = new Bitmap(code.Length * 12, 25);
Graphics g = Graphics.FromImage(image);
try
{
//清空图片背景色
g.Clear(Color.White);
//增加背景干扰线
Random random = new Random();
for (int i = 0; i < 30; 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.FromArgb(255, 212, 231)), x1, y1, x2, y2);
//g.DrawLine(new Pen(Color.FromArgb(120, 150, 210)), x1, y1, x2, y2);
}
//定义验证码字体
Font font = new Font("Arial", 10, (FontStyle.Bold | FontStyle.Italic | FontStyle.Strikeout));
//定义验证码的刷子,这里采用渐变的方式,颜色可自定义
LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.FromArgb(67, 93, 230), Color.FromArgb(70, 128, 228), 1.5f, true);
//增加干扰点
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()));
}
//将验证码写入图片
g.DrawString(code, font, brush, 5, 5);
//图片边框
g.DrawRectangle(new Pen(Color.FromArgb(93, 142, 228)), 0, 0, image.Width - 1, image.Height - 1);
//保存图片数据
MemoryStream stream = new MemoryStream();
//image.Save("C:/Users/admin/Desktop/省平台/a.jpeg", System.Drawing.Imaging.ImageFormat.Jpeg);
image.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
return stream.ToArray();
}
finally
{
g.Dispose();
image.Dispose();
}
}
四、最后效果图
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/ca93cdbbf08cd1c3e5d437b3167df313.jpeg#pic_center)