在.net core web项目中生成图片验证码
2018-12-19 15:14 tshaoguo 阅读(777) 评论(0) 编辑 收藏 举报第1步:添加SkiaSharp包引用
Install-Package SkiaSharp
第2步:编写生成图片验证码的代码
using SkiaSharp; //在类文件头部添加引用
public IActionResult Code()
{
string CodeText = "3bm7"; //实际的项目中不能写死
var charList = CodeText.ToList();
SKBitmap bmp = new SKBitmap(80,30);
using (SKCanvas canvas = new SKCanvas(bmp))
{
//背景色
canvas.DrawColor(SKColors.White);
using (SKPaint sKPaint = new SKPaint())
{
sKPaint.TextSize = 16;//字体大小
sKPaint.IsAntialias = true;//开启抗锯齿
sKPaint.Typeface = SKTypeface.FromFamilyName("微软雅黑");
SKRect size = new SKRect();
//计算文字宽度以及高度
sKPaint.MeasureText(charList[0].ToString(), ref size);
float temp = (bmp.Width / 4 - size.Size.Width) / 2;
float temp1 = bmp.Height - (bmp.Height - size.Size.Height) / 2;
Random random = new Random();
//画文字
for (int i = 0; i < 4; i++)
{
sKPaint.Color = new SKColor((byte)random.Next(0, 255), (byte)random.Next(0, 255), (byte)random.Next(0, 255));
canvas.DrawText(charList[i].ToString(), temp + 20 * i, temp1, sKPaint);
}
//画干扰线
for (int i = 0; i < 5; i++)
{
sKPaint.Color = new SKColor((byte)random.Next(0, 255), (byte)random.Next(0, 255), (byte)random.Next(0, 255));
canvas.DrawLine(random.Next(0, 40), random.Next(1, 29), random.Next(41, 80), random.Next(1, 29), sKPaint);
}
}
//页面展示图片
using (SKImage img = SKImage.FromBitmap(bmp))
{
using (SKData p = img.Encode())
{
return File(p.ToArray(), "image/Png");
}
}
}
}
第3步:运行测试