当前位置:   article > 正文

.netCore 图形验证码,非System.Drawing.Common_sixlabors.imagesharp 验证码

sixlabors.imagesharp 验证码

netcore需要跨平台,说白点就是放在windows服务器要能用,放在linux服务器上也能用,甚至macos上。

很多时候需要使用到图形验证码,这就有问题了。

旧方案

1.引入包

    <PackageReference Include="System.Drawing.Common" Version="5.0.3" />

2.添加引用

  1. using System.Drawing;
  2. using System.Drawing.Drawing2D;
  3. using System.Drawing.Imaging;

3.在linux上安装libgdiplus

问题在于这个libgdiplus东西非常大,这个东西是moon兼容而来的,而且!!!.net6.0开始不支持这个东西了。

新方案

1.安装包

    <PackageReference Include="SixLabors.ImageSharp.Drawing" Version="1.0.0-beta15" />

要勾选预览版,不然找不到这个包

2.添加引用

  1. using SixLabors.Fonts;
  2. using SixLabors.ImageSharp;
  3. using SixLabors.ImageSharp.Drawing.Processing;
  4. using SixLabors.ImageSharp.Formats.Jpeg;
  5. using SixLabors.ImageSharp.PixelFormats;
  6. using SixLabors.ImageSharp.Processing;

3.生成一个验证码图片

  1. public byte[] CreateByteByImgVerifyCode(string verifyCode, int width, int height)
  2. {
  3. using Image image = new Image<Rgba32>(width, height);
  4. //漆底色白色
  5. image.Mutate(x => x.DrawLines(Pens.DashDot(Color.White, width), new PointF[] { new PointF() { X = 0, Y = 0 }, new PointF() { X = width, Y = height } }));
  6. FontCollection collection = new();
  7. FontFamily family = collection.Add("font/font.ttf");
  8. Font font = family.CreateFont(20, FontStyle.Bold);
  9. PointF startPointF = new PointF(5, 5);
  10. Random random = new Random(); //随机数产生器
  11. 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 };
  12. //绘制大小
  13. for (int i = 0; i < verifyCode.Length; i++)
  14. {
  15. image.Mutate(x => x.DrawText(verifyCode[i].ToString(), font, colors[random.Next(colors.Length)], startPointF));
  16. //Console.WriteLine($"draw code:{verifyCode[i]} point:{startPointF.X}-{startPointF.Y}");
  17. startPointF.X += (int)(width - 10) / verifyCode.Length;
  18. startPointF.Y = random.Next(5, 10);
  19. }
  20. IPen pen = Pens.DashDot(Color.Silver, 1);
  21. //绘制干扰线
  22. for (var k = 0; k < 40; k++)
  23. {
  24. PointF[] points = new PointF[2];
  25. points[0] = new PointF(random.Next(width), random.Next(height));
  26. points[1] = new PointF(random.Next(width), random.Next(height));
  27. image.Mutate(x => x.DrawLines(pen, points));
  28. }
  29. using MemoryStream stream = new MemoryStream();
  30. image.Save(stream, JpegFormat.Instance);
  31. //输出图片流
  32. return stream.ToArray();
  33. }

4.在controller中调用它

  1. [HttpGet]
  2. public FileContentResult Code(string guid)
  3. {
  4. try
  5. {
  6. if (String.IsNullOrEmpty(guid))
  7. {
  8. throw new Exception("验证码代码错误,guid不能为空!");
  9. }
  10. //进行特殊符号的替换工作
  11. if (!new System.Text.RegularExpressions.Regex("[0-9,a-z,A-Z]{16}").Match(guid).Success)
  12. {
  13. throw new Exception("guid的位数不足,应为16位随机数,不能包含特殊符号,需要为字母和数字的组合");
  14. }
  15. if (_cache.KeyExits(string.Format(PublicString.CacheImageHead, guid))) { throw new Exception("guid不能重复使用!"); }
  16. //判断guid是否存在
  17. string code = _imgHelper.CreateVerifyCode(ImageHelper.VerifyCodeType.NumberVerifyCode);
  18. _cache.SetString(string.Format(PublicString.CacheImageHead, guid), code, 300);
  19. byte[] codeImage = _imgHelper.CreateByteByImgVerifyCode(code, 80, 36);
  20. return File(codeImage, @"image/jpeg");
  21. }
  22. catch (Exception exl)
  23. {
  24. _logger.LogException(exl);
  25. throw new Exception(exl.Message);
  26. }
  27. }

5.随机数计算,缓存帮助类自己实现。

6.新方案不需要安装libgdiplus

7.旧方案占用内存很大,新方案内存消耗很划算

附上一个Dockerfile的文件内容

  1. FROM mcr.microsoft.com/dotnet/aspnet:6.0-alpine AS base
  2. # 安装tzdata
  3. RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.aliyun.com/g' /etc/apk/repositories
  4. RUN apk add --no-cache tzdata
  5. #RUN apk add libgdiplus --update-cache --repository http://dl-3.alpinelinux.org/alpine/edge/testing/ --allow-untrusted
  6. #RUN apk add terminus-font
  7. # 设置时区
  8. ENV TZ="Asia/Shanghai"
  9. ENV LANG C.UTF-8
  10. FROM base AS final
  11. WORKDIR /app
  12. EXPOSE 80
  13. COPY . .
  14. ENTRYPOINT ["dotnet", "xxx.HttpApi.Host.dll"]

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/花生_TL007/article/detail/125109
推荐阅读
相关标签
  

闽ICP备14008679号