codebude / QRCoder

A pure C# Open Source QR Code implementation
MIT License
4.66k stars 1.11k forks source link

Qrcode with logo or Icon #579

Closed aklegend closed 1 month ago

aklegend commented 2 months ago

How to add logo or icon to the qr code can anyone share the code to show qrcode with logo into the picturebox

by using this code i can generate and show image into the picturebox but without logo in center.

using (QRCodeGenerator qrGenerator = new QRCodeGenerator()) using (QRCodeData qrCodeData = qrGenerator.CreateQrCode(Qrtext.ToString(), QRCodeGenerator.ECCLevel.Q)) using (PngByteQRCode qrCode = new PngByteQRCode(qrCodeData)) { byte[] qrCodeImage = qrCode.GetGraphic(20); using (MemoryStream ms = new MemoryStream(qrCodeImage)) { pictureBox1.Image = Image.FromStream(ms); } }

ralfbalzer commented 1 month ago

@aklegend I can only give you a solution that uses Bitmap (so it only works in QrCoder up to version 1.4.2 with System Drawing version 7.0.0. - see open issues) This works for me:

public QrCodeGenerator Get(string qrText)
    {
        QRCodeGenerator _qrGenerator = new();
        qrText = qrText.ToUtf8().RemoveDiacritics();
        QRCodeData _qrCodeData = _qrGenerator.CreateQrCode(qrText, QRCodeGenerator.ECCLevel.Q);
        QRCode _qrCode = new(_qrCodeData);
        Bitmap = _qrCode.GetGraphic(20, Color.Black, Color.White, (Bitmap)Image.FromFile(Path.Combine(HostEnvironment.WebRootPath, "images", "icons", "xxx-image-name.png")));
        return this;
    }
codebude commented 1 month ago

@aklegend I can only give you a solution that uses Bitmap (so it only works in QrCoder up to version 1.4.2 with System Drawing version 7.0.0. - see open issues)

That's not 100% correct. It works also with the latest QRCoder release (v1.6.0). Just just have to target your project either < net6.0 or especially target against net6.0-windows. The reason therefore is that all the icon/logo related parts rely on System.Drawing which was dropped by Microsoft from net6.0 for non-Windows targets. So if you aim your project towards net6.0-windows (or use older target) everything should work as expected. How to target: https://learn.microsoft.com/en-us/visualstudio/ide/visual-studio-multi-targeting-overview?view=vs-2022

Besides the QRCode rendering class there are also other renderers that support icons/logos, e.g. Base64QRCode and SvgQRCode. For more details check the documentation: https://github.com/codebude/QRCoder/wiki/Advanced-usage---QR-Code-renderers (And search for "logo" and "icon".)