Generating QR codes and barcodes in .NET

 
 
  • Gérald Barré

In this post, we'll explore Meziantou.Framework.Barcodes and Meziantou.Framework.Imaging.Barcodes. These packages, under MIT license, allow you to generate QR codes and linear barcodes, render them as SVG, images, or console text, and draw them on existing images.

Meziantou.Framework.Barcodes implements the QR code specification from scratch. No third-party dependencies are required for the core generation logic. Typical use cases are:

  • Printing a QR code on a ticket, an invoice, or a label to link to a page or identify an item
  • Generating product barcodes (EAN-13, UPC-A) or logistics barcodes (Code 128)
  • Sharing Wi-Fi credentials, a contact, or a two-factor authentication setup with a QR code that phones understand
  • Displaying a QR code in the terminal from a command-line tool

#Installation

Install the NuGet package:

Shell
dotnet package add Meziantou.Framework.Barcodes

The types are in the Meziantou.Framework.Barcodes namespace.

#QR codes

The library supports three QR code variants:

TypeMethodSize
Standard QRQRCode.Create(...)21x21 to 177x177
Micro QRQRCode.CreateMicroQR(...)11x11 to 17x17
Rectangular Micro QR (rMQR)QRCode.CreateRMQR(...)Narrow rectangular
C#
// Standard QR code
var standardQr = QRCode.Create("HELLO WORLD", ErrorCorrectionLevel.H);

// Micro QR code (smaller, single finder pattern)
var microQr = QRCode.CreateMicroQR("12345", ErrorCorrectionLevel.L);

// Rectangular Micro QR (narrow rectangular shape)
var rmqr = QRCode.CreateRMQR("https://www.meziantou.net", ErrorCorrectionLevel.M);

#Barcodes

The library supports the following linear barcode formats:

TypeMethodNotes
Code 39Barcode.CreateCode39(...)Optional Mod 43 checksum
Code 93Barcode.CreateCode93(...)Standard and extended encoding
Code 128Barcode.CreateCode128(...)Auto switches to Code Set C for numeric runs
EAN-8Barcode.CreateEan8(...)Optional 2/5-digit add-on extension
EAN-13Barcode.CreateEan13(...)Optional 2/5-digit add-on extension
UPC-ABarcode.CreateUpcA(...)Optional 2/5-digit add-on extension
CodabarBarcode.CreateCodabar(...)Configurable start/stop guards
ITFBarcode.CreateItf(...)Numeric payloads, even digit count
C#
var code39  = Barcode.CreateCode39("ABC-123", includeChecksum: true);
var code93  = Barcode.CreateCode93("ABC123");
var code128 = Barcode.CreateCode128("SKU-123456");
var ean8    = Barcode.CreateEan8("5512345");
var ean13   = Barcode.CreateEan13("400638133393");
var upcA    = Barcode.CreateUpcA("03600029145", extension: "12");
var codabar = Barcode.CreateCodabar("40156", startCharacter: 'A', stopCharacter: 'B');
var itf     = Barcode.CreateItf("12345678");

#Rendering

##SVG

SVG output is great for the web because it scales to any size without quality loss. The QR code renderer also supports embedding a logo in the center. The colors are SceneColor values from the Meziantou.Framework.VectorGraphics namespace.

C#
// QR code with custom colors and a centered logo
var svg = standardQr.ToSvg(new QRCodeRenderOptions
{
    ModuleSize = 10,
    QuietZoneModules = 4,
    DarkPaint = new SceneColor(0x00, 0x00, 0x00),
    LightPaint = new SceneColor(0xff, 0xff, 0xff),
    // A PNG, JPEG, GIF, or WebP file: the SVG embeds it
    Logo = new BarcodeLogo(File.ReadAllBytes("logo.png"))
    {
        SizePercent = 20,
    },
});

// Barcode as SVG
var barcodeSvg = code128.ToSvg(new BarcodeRenderOptions
{
    ModuleWidth = 2,
    ModuleHeight = 80,
    QuietZoneModules = 10,
});

Every symbol is drawn as a vector scene, and the SVG renderer is one way to output it. The same options produce PNG, WebP, or JPEG images with Meziantou.Framework.Imaging.Barcodes, as shown later in this post.

##Console

The console renderer outputs QR codes and barcodes using Unicode block characters. You can adjust module width and height to make the output more square in most terminal fonts.

C#
standardQr.WriteToConsole();

var text = microQr.ToConsoleString(new ConsoleRenderOptions
{
    QuietZoneModules = 1,
    ModuleWidth = 2,
    ModuleHeight = 2,
});
Console.WriteLine(text);

#Content helpers

QRCodePayload provides static helpers that format payloads for common use cases. These produce correctly encoded strings ready to pass directly to QRCode.Create.

C#
// WiFi network credentials
var wifi = QRCodePayload.Wifi("MyNetwork", "password123", WifiAuthentication.WPA);

// vCard contact
var vcard = QRCodePayload.VCard("Doe", "John", phone: "+1234567890", email: "john@example.com");

// MeCard contact (compact format)
var mecard = QRCodePayload.MeCard("Doe", "John", phone: "+1234567890");

// Email
var email = QRCodePayload.Email("test@example.com", subject: "Hello");

// Phone / SMS
var phone = QRCodePayload.Phone("+1234567890");
var sms   = QRCodePayload.Sms("+1234567890", "Hello!");

// Geolocation
var geo = QRCodePayload.Geolocation(48.8566, 2.3522);

// Calendar event
var evt = QRCodePayload.CalendarEvent("Meeting",
    new DateTime(2025, 6, 15, 14, 0, 0, DateTimeKind.Utc),
    new DateTime(2025, 6, 15, 15, 0, 0, DateTimeKind.Utc),
    location: "Room 42");

// OTP Auth (2FA setup)
var otp = QRCodePayload.OneTimePassword(OneTimePasswordType.Totp,
    "JBSWY3DPEHPK3PXP", "user@example.com", issuer: "MyApp");

// Bitcoin payment
var btc = QRCodePayload.Bitcoin("1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa", amount: 0.05m);

// SEPA payment (EPC QR)
var sepa = QRCodePayload.SepaPayment("Example", "DE00000000000000000000", 12.50m,
    remittanceText: "Donation");

// Use the payload with a QR code
var qr = QRCode.Create(wifi, ErrorCorrectionLevel.M);

#Rendering with Meziantou.Framework.Imaging

When you need a PNG file or another image format (WebP, JPEG, AVIF, etc.), want to process the image further, or want to add a QR code to an existing image, use Meziantou.Framework.Imaging.Barcodes. It draws the same vector scene as the SVG renderer, with the same options, as Meziantou.Framework.Imaging images.

Shell
dotnet package add Meziantou.Framework.Imaging.Barcodes

The types are in the Meziantou.Framework.Imaging.Barcodes namespace. The examples also use the Meziantou.Framework.VectorGraphics (colors), Meziantou.Framework.Imaging (images), and Meziantou.Framework.Imaging.Formats (encoders) namespaces.

##Images in any format

ToImage returns an Image<Rgba32> that you can save in any format the imaging library supports. The image must be disposed.

C#
var qrCode = QRCode.Create("https://www.meziantou.net", ErrorCorrectionLevel.M);

// Default options: 10 pixels per module, a 4-module quiet zone, black on white
using var image = qrCode.ToImage();
image.Save("qrcode.webp", new WebPEncoder());

// The same options as the SVG renderer: custom color, and a transparent background
using var customImage = qrCode.ToImage(new QRCodeRenderOptions
{
    ModuleSize = 4,
    QuietZoneModules = 2,
    DarkPaint = new SceneColor(0x00, 0x33, 0x66),
    LightPaint = null,
});
customImage.Save("qrcode-transparent.png", new PngEncoder { PixelLayout = PngPixelLayout.Indexed });

// Barcodes work the same way
var barcode = Barcode.CreateEan13("5901234123457");
using var barcodeImage = barcode.ToImage(new BarcodeRenderOptions { ModuleWidth = 3, ModuleHeight = 100 });
barcodeImage.Save("barcode.jpg", new JpegEncoder());

Setting LightPaint to null keeps the background, so the image is transparent around the dark modules. An indexed PNG stores the two colors in a palette, which keeps the file small.

##Drawing on an existing image

DrawQRCode and DrawBarcode draw on the canvas of Image.Draw. The modules are drawn as vector shapes, so the transform, the clip, and the layers of the canvas apply, and any paint (color, gradient, pattern) can fill them. MeasureQRCode and MeasureBarcode return the size of the drawing, so you can lay out the image before drawing. For instance, here is how to add a QR code in the top-right corner of a ticket:

C#
using var ticket = Image.Load<Rgba32>("ticket.png");
var qrCode = QRCode.Create("TICKET-0042");
var options = new QRCodeRenderOptions { ModuleSize = 4, QuietZoneModules = 2 };

// Size of the drawing, quiet zone included: (21 modules + 2 x 2) x 4 = 100 pixels
var size = QRCodeImageRenderer.MeasureQRCode(qrCode, options);

const int Margin = 16;
ticket.Draw(canvas => canvas.DrawQRCode(qrCode, new PointD(ticket.Width - Margin - size.Width, Margin), options));
ticket.Save("ticket-with-qrcode.png");

By default, SnapToPixels rounds the module size and the position to whole pixels. Every module has the same size and sharp edges, which is what scanners read best. Set it to false to draw at the exact size and position, for instance when the canvas is scaled or rotated.

##Human-readable text under barcodes

Barcodes printed on products usually show their value under the bars. When you set BarcodeRenderOptions.Text, DrawBarcode, ToImage, and ToSvg print Barcode.Text under the bars. This text includes the characters the encoder adds, such as the check digit of an EAN-13 barcode.

C#
var barcode = Barcode.CreateEan13("590123412345");
var options = new BarcodeRenderOptions
{
    ModuleWidth = 2,
    ModuleHeight = 60,
    QuietZoneModules = 9,
    Text = new BarcodeTextOptions { Fonts = BarcodeFonts.OcrB, FontSize = 24 }, // Prints "5901234123457" under the bars
};

using var label = new Image<Rgba32>(300, 140, Colors.White);
label.Draw(canvas => canvas.DrawBarcode(barcode, new PointD(20, 20), options));
label.Save("label.png");

Meziantou.Framework.Barcodes bundles the two fonts of optical character recognition: BarcodeFonts.OcrA and BarcodeFonts.OcrB. OCR-B is the font usually printed under EAN and UPC barcodes. Both fonts are generated from the character shapes defined in the ANSI standards and are licensed with the package, so you don't need to find and ship a font file yourself.

#Additional resources

This post is part of the series 'Exploring Meziantou.Framework'. Be sure to check out the rest of the blog posts of the series!

Show the 22 posts of the series

Do you have a question or a suggestion about this post? Contact me!

Follow me:
Enjoy this blog?