C# 打印QR Code

private Bitmap GenerateQRCodeWithTextOnRight(string text, int qrCodeSize, Font textFont, Color textColor)
{
    // 创建 QR 码写入器  
    var writer = new BarcodeWriter
    {
        Format = BarcodeFormat.QR_CODE,
        Options = new QrCodeEncodingOptions
        {
            Height = qrCodeSize,
            Width = qrCodeSize,
            Margin = 0,
            NoPadding = true,
        }
    };

    // 生成 QR 码图像  
    Bitmap qrCodeBitmap = writer.Write(text);

    // 计算文本所需宽度(使用 Graphics.MeasureString 方法)  
    using (Graphics graphics = Graphics.FromImage(new Bitmap(1, 1))) // 创建一个临时的 Graphics 对象来测量文本  
    {
        SizeF textSize = graphics.MeasureString(text, textFont);
        int textWidth = (int)Math.Ceiling(textSize.Width); // 向上取整,确保文本不会因舍入而截断  

        // 计算总宽度(QR 码宽度 + 文本宽度 + 一些间距)  
        int totalWidth = qrCodeBitmap.Width + textWidth + 10; // 10 是 QR 码和文本之间的间距  

        // 创建一个新的 Bitmap 来存放 QR 码和文本  
        Bitmap resultBitmap = new Bitmap(totalWidth, qrCodeBitmap.Height);

        // 使用 Graphics 对象来绘制 QR 码和文本  
        using (Graphics g = Graphics.FromImage(resultBitmap))
        {
            // 绘制 QR 码  
            g.DrawImage(qrCodeBitmap, 0, 0);

            // 绘制文本  
            // 注意:这里我们使用文本的左上角作为起点,并调整 x 坐标以将其放置在 QR 码右侧  
            g.DrawString(text, textFont, new SolidBrush(textColor), qrCodeBitmap.Width + 5, 0); // +5 是 QR 码和文本之间的额外间距  
        }

        // 返回包含 QR 码和文本的 Bitmap  
        return resultBitmap;
    }

    // 注意:在这个特定的示例中,qrCodeBitmap.Dispose() 是不必要的,因为当 Graphics 对象被释放时,  
    // 它不会持有对 qrCodeBitmap 的任何引用,并且 qrCodeBitmap 很快就会被垃圾回收。  
    // 然而,在更复杂的情况下,显式释放资源总是一个好习惯。  
}

调佣

 Bitmap qrCodeWithText = GenerateQRCodeWithTextOnRight(txtConent.Text.Trim(), pixelSize, textFont, textColor);

 // 现在你可以将 qrCodeWithText 保存为文件或进行其他处理

 picQRcode.Image = qrCodeWithText;
 picQRcode.Height = qrCodeWithText.Height;
 picQRcode.Width = qrCodeWithText.Width;

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值