Search code examples
c#.net-coreqr-codezxingzxing.net

ZXing QrCode renderer exception with .Net Core 2.1


I would like to create a QR code with using ZXing(0.16.4) But I meet following exception,

System.InvalidOperationException: 'You have to set a renderer instance.'

Almost the same code works well with .Net Framework 4.6.1

here is my code

static void Main(string[] args)
{
    var qrCode = CreateQrCode("test");
    Console.ReadKey();
}

public static byte[] CreateQrCode(string content)
{
    BarcodeWriter<Bitmap> writer = new BarcodeWriter<Bitmap>
    {
        Format = BarcodeFormat.QR_CODE,
        Options = new QrCodeEncodingOptions
        {
            Width = 100,
            Height = 100,
        }
    };

    var qrCodeImage = writer.Write(content); // BOOM!!

    using (var stream = new MemoryStream())
    {
        qrCodeImage.Save(stream, ImageFormat.Png);
        return stream.ToArray();
    }
}

Solution

  • I solved the issue, Basically I used https://www.nuget.org/packages/ZXing.Net.Bindings.CoreCompat.System.Drawing

    I create BarcodeWriter generated from following namespace

    ZXing.CoreCompat.System.Drawing

    here is my CreateQrCode method

    public static byte[] CreateQrCode(string content)
    {
        BarcodeWriter writer = new BarcodeWriter
        {
            Format = BarcodeFormat.QR_CODE,
            Options = new QrCodeEncodingOptions
            {
                Width = 100,
                Height = 100,
            }
        };
    
        var qrCodeImage = writer.Write(content); // BOOM!!
    
        using (var stream = new MemoryStream())
        {
            qrCodeImage.Save(stream, ImageFormat.Png);
            return stream.ToArray();
        }
    }
    

    Here is the read QR code method, maybe someone will need as well. BarcodeReader also generated from the same namespace like create.

    Here is the method

    public static string ReadQrCode(byte[] qrCode)
    {
        BarcodeReader coreCompatReader = new BarcodeReader();
    
        using (Stream stream = new MemoryStream(qrCode))
        {
            using (var coreCompatImage = (Bitmap)Image.FromStream(stream))
            {
                return coreCompatReader.Decode(coreCompatImage).Text;
            }
        }
    }
    

    Hope this answer will protect someone's hair against pulling.