当前位置:   article > 正文

C# 跨平台 二维码生成和读取_skbitmap设置utf-8

skbitmap设置utf-8

1.使用的NuGet包有:

ZXing.Net.Bindings.SkiaSharp

SkiaSharp

SkiaSharp.NativeAssets.Linux

2.代码实现:

  1. using ZXing.SkiaSharp;
  2. using ZXing;
  3. using ZXing.QrCode;
  4. using SkiaSharp;
  5. public static class QrCode
  6. {
  7. public enum Type
  8. {
  9. Qr,
  10. Bar
  11. }
  12. //生成二维码
  13. public static void GetQrCode(string text, string fileName, int width = 200, int height = 200, int margin = 1, Type type = Type.Qr, bool pureBarcode = true)
  14. {
  15. QrCodeEncodingOptions options = new QrCodeEncodingOptions()
  16. {
  17. CharacterSet = "UTF-8",
  18. Width = width,
  19. Height = height,
  20. Margin = 1,
  21. PureBarcode = pureBarcode
  22. };
  23. BarcodeWriter writer = new();
  24. if (type == Type.Bar) { writer.Format = ZXing.BarcodeFormat.CODE_128; }//条形码,不能出现中文字
  25. else { writer.Format = ZXing.BarcodeFormat.QR_CODE; } //二维码
  26. writer.Options = options;
  27. var bitmap = writer.Write(text);
  28. // 将图片编码为字节数组
  29. using (var memoryStream = new MemoryStream())
  30. {
  31. bitmap.Encode(memoryStream, SKEncodedImageFormat.Png, 100);
  32. byte[] imageData = memoryStream.ToArray();
  33. // 将字节数组写入文件
  34. File.WriteAllBytes(fileName, imageData);
  35. }
  36. }
  37. public static byte[] GetQrCode(string text,int width=200,int height = 200,int margin=1, Type type=Type.Qr,bool pureBarcode =true)
  38. {
  39. QrCodeEncodingOptions options = new QrCodeEncodingOptions()
  40. {
  41. CharacterSet = "UTF-8",
  42. Width = width,
  43. Height = height,
  44. Margin = 1,
  45. PureBarcode = pureBarcode
  46. };
  47. BarcodeWriter writer = new();
  48. if (type == Type.Bar){ writer.Format = ZXing.BarcodeFormat.CODE_128; }//条形码,不能出现中文字
  49. else { writer.Format = ZXing.BarcodeFormat.QR_CODE; } //二维码
  50. writer.Options = options;
  51. var bitmap = writer.Write(text);
  52. // 将图片编码为字节数组
  53. var memoryStream = new MemoryStream();
  54. bitmap.Encode(memoryStream, SKEncodedImageFormat.Png, 100);
  55. return memoryStream.ToArray();
  56. }
  57. //识别二维码
  58. public static string ReadQrCode(string filename)
  59. {
  60. string ret = "";
  61. BarcodeReader reader = new BarcodeReader();
  62. reader.Options.CharacterSet = "UTF-8";
  63. Stream stream = File.OpenRead(filename);
  64. SKBitmap bitmap = SKBitmap.Decode(stream);
  65. Result result = reader.Decode(bitmap);
  66. ret = result == null ? "" : result.Text;
  67. return ret;
  68. }
  69. }

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

闽ICP备14008679号