Create QR Codes with .NET
QR codes are a simple and very popular way of exchanging data and information - even in .NET. They have become part of everyday life.
Unfortunately, .NET does not natively support the generation of QRCodes; we have to rely on the community. Fortunately, there is a very good library that we can use: QRCoder by Raffael Herrmann.
Install QRCoder
The installation is simple. We can install the library via NuGet:
dotnet add package QRCoder
Using QRCoder
The structure and use of the library is very simple: we basically just need to create an instance of the QRCodeGenerator
class and call the CreateQrCode
method. The CreateQrCode
method returns a QRCodeData
object, which we can then convert into a Bitmap
object.
A more realistic example is that we abstract the generation of the QRCode into a provider, which allows us to separate the implementation from the use and also to implement unit tests more easily.
// Defining the QRCodeProvider class
// Add an interface to your code!
public class QRCodeProvider
{
// Creating a new instance of QRCodeGenerator
// In principle, this class supports IDisposable, but we can re-use this instance
private static readonly QRCodeGenerator s_qrGenerator = new();
// Method to generate the QR code
public byte[] GeneratePng(string text)
{
// Creating the QR code data with our defaults
using QRCodeData qrCodeData = s_qrGenerator.CreateQrCode(text, QRCodeGenerator.ECCLevel.Q);
// Creating a new instance of PngByteQRCode with the QR code data
// We can also use other Image types, like BitmapByteQRCode
PngByteQRCode qrCode = new (qrCodeData);
// Returning the QR code as a graphic
return qrCode.GetGraphic(pixelsPerModule: 20);
}
}
The QRCodeProvider
class can now either be used directly or integrated cleanly into a dependency injection container with an additional interface.
By calling the provider, we can generate our QRCode as a PNG with a handful of code - in this example stored on the file system.
// NuGet: https://github.com/codebude/QRCoder
using QRCoder;
namespace BenjaminAbt_Samples_QrCode // Defining the namespace
{
internal class Program // Defining the Program class
{
static void Main(string[] args)
{
// Creating a new instance of QRCodeProvider
// This is our own abstraction
QRCodeProvider qrCodeProvider = new();
// Defining the path where the QR code will be saved
// You can use different types of images and also svg or In-Memory
string path = @"C:\temp\qrcodetest.png";
string sampleText = "Hello World";
// Generating the QR code
byte[] png = qrCodeProvider.GeneratePng(sampleText);
File.WriteAllBytes(path, png); // Writing the QR code to the file
}
}
// QRCodeProvider here
}