利用ZXing.Net生成二维码,支持带logo二维码

       二维码作为一种能携带很多信息的图片,在很多场景都有使用。常见的支付码、微信个人二维码等等。在医疗场景中也有一些使用,例如处方单、报告单上放置一个二维码,可以扫码查看电子处方单、电子报告等。

       用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;
        }
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值