Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
    }
}
like image 755
arslanaybars Avatar asked Oct 03 '18 06:10

arslanaybars


2 Answers

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.

like image 188
arslanaybars Avatar answered Oct 03 '22 12:10

arslanaybars


There is a newer version of the package available and it works with .NET Core 3.1.

https://www.nuget.org/packages/ZXing.Net.Bindings.Windows.Compatibility/

like image 32
user2577288 Avatar answered Oct 03 '22 11:10

user2577288