二维码作为一种能携带很多信息的图片,在很多场景都有使用。常见的支付码、微信个人二维码等等。在医疗场景中也有一些使用,例如处方单、报告单上放置一个二维码,可以扫码查看电子处方单、电子报告等。
用ZXing.Net第三方组件实现生成和解析二维码,同时支持带logo形式的二维码,话不多说,直接上代码。
public class QRCodeHelper
{
/// <summary>
/// 使用zxing动态库生成二维码
/// </summary>
/// <param name="conetnt">二维码内容</param>
/// <param name="errorMessage">异常信息</param>
/// <param name="logoPath">logo图片路径,默认为空。为空时生成的二维码不带logo</param>
/// <param name="height">二维码图片高度,默认240 单位 pixels</param>
/// <param name="width">二维码图片宽度,默认240 单位 pixels</param>
/// <param name="margin">二维码图片边距,默认为0</param>
/// <returns></returns>
public static Bitmap GenerateQRCode(string conetnt, out string errorMessage, string logoPath = "", int height = 240, int width = 240, int margin = 0)
{
errorMessage = string.Empty;
try
{
BarcodeWriter barCodeWriter = new BarcodeWriter();
barCodeWriter.Format = BarcodeFormat.QR_CODE;
barCodeWriter.Options.Hints.Add(EncodeHintType.CHARACTER_SET, "UTF-8");
barCodeWriter.Options.Hints.Add(EncodeHintType.ERROR_CORRECTION, ZXing.QrCode.Internal.ErrorCorrectionLevel.H);
barCodeWriter.Options.Height = height;
barCodeWriter.Options.Width = width;
barCodeWriter.Options.Margin = margin;
BitMatrix bm = barCodeWriter.Encode(conetnt);
Bitmap qrCodeImage = barCodeWriter.Write(bm);
if (!string.IsNullOrEmpty(logoPath))
{
// 添加Logo
Bitmap logo = new Bitmap(logoPath);
int logoSize = (int)(qrCodeImage.Width * 0.2); // Logo大小为二维码大小的1/5
int logoX = (qrCodeImage.Width - logoSize) / 2;
int logoY = (qrCodeImage.Height - logoSize) / 2;
Graphics qrGraphics = Graphics.FromImage(qrCodeImage);
qrGraphics.DrawImage(logo, new Rectangle(logoX, logoY, logoSize, logoSize));
}
return qrCodeImage;
}
catch (Exception ex)
{
errorMessage = $"Exception raised when generating QRCode,, Exception;{ex}";
return null;
}
}
/// <summary>
/// 使用zxing动态库解析
/// </summary>
/// <param name="image">二维码图像</param>
/// <returns></returns>
public static string ParseBarCode(Bitmap image)
{
BarcodeReader reader = new BarcodeReader();
Result result = reader.Decode(image);
return result.Text;
}
}