使用跨平台库SixLabors.ImageSharp.Drawing生成图片验证码
/// <summary> /// 绘制图片验证码 /// </summary> /// <param name="webRootPath"></param> /// <param name="width"></param> /// <param name="height"></param> /// <returns></returns> public static string GenerateImgVerifyCode(string verifyCode, int width = 120, int height = 50) { ////根据验证码的长度确定输出图片的宽度 //int iWidth = (int)Math.Ceiling(verifyCode.Code.Length * 15m); using Image image = new Image<Rgba32>(width, height); //漆底色白色 image.Mutate(x => x.DrawLine(Pens.DashDot(Color.White, width), new PointF[] { new PointF() { X = 0, Y = 0 }, new PointF() { X = width, Y = height } })); FontCollection collection = new(); //加载字体 FontFamily family = collection.Add("./wwwroot/FZHTJW.TTF"); Font font = family.CreateFont(20, FontStyle.Bold); PointF startPointF = new PointF(5, 5); Random random = new Random(); //随机数产生器 Color[] colors = new Color[] { Color.Red, Color.Blue, Color.Green, Color.Purple, Color.Peru, Color.LightSeaGreen, Color.Lime, Color.Magenta, Color.Maroon, Color.MediumBlue, Color.MidnightBlue, Color.Navy }; //绘制验证码 for (int i = 0; i < verifyCode.Length; i++) { image.Mutate(x => x.DrawText(verifyCode[i].ToString(), font, colors[random.Next(colors.Length)], startPointF)); startPointF.X += (int)(width - 10) / verifyCode.Length; startPointF.Y = random.Next(5, 10); } var pen = Pens.DashDot(Color.Silver, 1); //绘制银色背景噪音线30条 for (var k = 0; k < 30; k++) { PointF[] points = new PointF[2]; points[0] = new PointF(random.Next(width), random.Next(height)); points[1] = new PointF(random.Next(width), random.Next(height)); image.Mutate(x => x.DrawLine(pen, points)); } using (MemoryStream stream = new MemoryStream()) { image.Save(stream, PngFormat.Instance); byte[] arr = new byte[stream.Length]; stream.Position = 0; stream.Read(arr, 0, (int)stream.Length); stream.Close(); return Convert.ToBase64String(arr); }; }
注意:准备字体库 “FZHTJW.TTF”