115 lines
3.6 KiB
C#
115 lines
3.6 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Drawing;
|
|
using System.Drawing.Imaging;
|
|
using ZXing;
|
|
using ZXing.Common;
|
|
using ZXing.QrCode;
|
|
using ZXing.QrCode.Internal;
|
|
using ZXing.Windows.Compatibility;
|
|
|
|
namespace Com.Lmc.ShuiYin.Two.Utils
|
|
{
|
|
public class QRCodeUtils
|
|
{
|
|
private int width;
|
|
private int height;
|
|
private string format;
|
|
private Dictionary<EncodeHintType, object> paramMap;
|
|
|
|
public QRCodeUtils()
|
|
{
|
|
this.width = 100;
|
|
this.height = 100;
|
|
this.format = "png";
|
|
this.paramMap = new Dictionary<EncodeHintType, object>();
|
|
this.paramMap.Add(EncodeHintType.CHARACTER_SET, "UTF-8");
|
|
this.paramMap.Add(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
|
|
this.paramMap.Add(EncodeHintType.MARGIN, 1);
|
|
}
|
|
|
|
public void SetFormat(string format)
|
|
{
|
|
this.format = format;
|
|
}
|
|
|
|
public void SetSize(int width, int height)
|
|
{
|
|
this.width = width;
|
|
this.height = height;
|
|
}
|
|
|
|
public void SetParam(EncodeHintType type, object param)
|
|
{
|
|
if (paramMap.ContainsKey(type))
|
|
{
|
|
paramMap[type] = param;
|
|
}
|
|
else
|
|
{
|
|
paramMap.Add(type, param);
|
|
}
|
|
}
|
|
|
|
public void QREncode(string content, string outPutFile)
|
|
{
|
|
BarcodeWriter writer = new BarcodeWriter
|
|
{
|
|
Format = BarcodeFormat.QR_CODE,
|
|
Options = new QrCodeEncodingOptions
|
|
{
|
|
Width = this.width,
|
|
Height = this.height,
|
|
CharacterSet = "UTF-8",
|
|
ErrorCorrection = (ErrorCorrectionLevel)paramMap[EncodeHintType.ERROR_CORRECTION],
|
|
Margin = (int)paramMap[EncodeHintType.MARGIN]
|
|
}
|
|
};
|
|
|
|
using (Bitmap bitmap = writer.Write(content))
|
|
{
|
|
ImageFormat imgFormat = ImageFormat.Png;
|
|
if (format.Equals("jpg", StringComparison.OrdinalIgnoreCase) || format.Equals("jpeg", StringComparison.OrdinalIgnoreCase))
|
|
imgFormat = ImageFormat.Jpeg;
|
|
else if (format.Equals("bmp", StringComparison.OrdinalIgnoreCase))
|
|
imgFormat = ImageFormat.Bmp;
|
|
|
|
bitmap.Save(outPutFile, imgFormat);
|
|
}
|
|
}
|
|
|
|
public Bitmap QREncode(string contents)
|
|
{
|
|
BarcodeWriter writer = new BarcodeWriter
|
|
{
|
|
Format = BarcodeFormat.QR_CODE,
|
|
Options = new QrCodeEncodingOptions
|
|
{
|
|
Width = this.width,
|
|
Height = this.height,
|
|
CharacterSet = "UTF-8",
|
|
ErrorCorrection = (ErrorCorrectionLevel)paramMap[EncodeHintType.ERROR_CORRECTION],
|
|
Margin = (int)paramMap[EncodeHintType.MARGIN]
|
|
}
|
|
};
|
|
return writer.Write(contents);
|
|
}
|
|
|
|
public string QRReader(string filePath)
|
|
{
|
|
using (Bitmap bitmap = (Bitmap)Image.FromFile(filePath))
|
|
{
|
|
return QRReader(bitmap);
|
|
}
|
|
}
|
|
|
|
public string QRReader(Bitmap bitmap)
|
|
{
|
|
BarcodeReader reader = new BarcodeReader();
|
|
// reader.Options.CharacterSet = "UTF-8";
|
|
Result result = reader.Decode(bitmap);
|
|
return result?.Text;
|
|
}
|
|
}
|
|
}
|