赞
踩
1.使用的NuGet包有:
ZXing.Net.Bindings.SkiaSharp
SkiaSharp
SkiaSharp.NativeAssets.Linux
2.代码实现:
- using ZXing.SkiaSharp;
- using ZXing;
- using ZXing.QrCode;
- using SkiaSharp;
-
- public static class QrCode
- {
- public enum Type
- {
- Qr,
- Bar
- }
- //生成二维码
- public static void GetQrCode(string text, string fileName, int width = 200, int height = 200, int margin = 1, Type type = Type.Qr, bool pureBarcode = true)
- {
-
- QrCodeEncodingOptions options = new QrCodeEncodingOptions()
- {
- CharacterSet = "UTF-8",
- Width = width,
- Height = height,
- Margin = 1,
- PureBarcode = pureBarcode
- };
- BarcodeWriter writer = new();
- if (type == Type.Bar) { writer.Format = ZXing.BarcodeFormat.CODE_128; }//条形码,不能出现中文字
- else { writer.Format = ZXing.BarcodeFormat.QR_CODE; } //二维码
- writer.Options = options;
-
- var bitmap = writer.Write(text);
- // 将图片编码为字节数组
- using (var memoryStream = new MemoryStream())
- {
- bitmap.Encode(memoryStream, SKEncodedImageFormat.Png, 100);
- byte[] imageData = memoryStream.ToArray();
- // 将字节数组写入文件
- File.WriteAllBytes(fileName, imageData);
- }
- }
- public static byte[] GetQrCode(string text,int width=200,int height = 200,int margin=1, Type type=Type.Qr,bool pureBarcode =true)
- {
- QrCodeEncodingOptions options = new QrCodeEncodingOptions()
- {
- CharacterSet = "UTF-8",
- Width = width,
- Height = height,
- Margin = 1,
- PureBarcode = pureBarcode
- };
- BarcodeWriter writer = new();
- if (type == Type.Bar){ writer.Format = ZXing.BarcodeFormat.CODE_128; }//条形码,不能出现中文字
- else { writer.Format = ZXing.BarcodeFormat.QR_CODE; } //二维码
- writer.Options = options;
- var bitmap = writer.Write(text);
- // 将图片编码为字节数组
- var memoryStream = new MemoryStream();
- bitmap.Encode(memoryStream, SKEncodedImageFormat.Png, 100);
- return memoryStream.ToArray();
- }
- //识别二维码
- public static string ReadQrCode(string filename)
- {
- string ret = "";
- BarcodeReader reader = new BarcodeReader();
- reader.Options.CharacterSet = "UTF-8";
- Stream stream = File.OpenRead(filename);
- SKBitmap bitmap = SKBitmap.Decode(stream);
- Result result = reader.Decode(bitmap);
- ret = result == null ? "" : result.Text;
- return ret;
- }
- }

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。