Skip to content
guitarrapcPublic

About

High-performance QR code generator/reader with renderes support

Topics

Resources

Stars

245 stars

Watchers

1 watching

Forks

Repository files navigation

Build release

License: MIT NuGet FeatherQR NuGet FeatherQR.SkiaSharp NuGet SkiaSharp.QrCode

FeatherQR

Playground | Migration | Data Capacity | Design Docs

FeatherQR generates and decodes QR Code, Micro QR, and rMQR symbols in .NET. The span overloads generate and decode without allocation, and all packages support trimming and NativeAOT. The core package has no dependencies on .NET 10 and later, and only BCL compatibility packages on .NET Standard. It does not use System.Drawing.

Instagram-style Gradient QR Icon QR
MicroQR static MicroQR styled
rMQR R9x139 with a fixed 9-module height

samples/ConsoleApp has the code for these images. The benchmarks compare FeatherQR with other libraries:

Encode Performance Decode Performance

Features

Symbology Standard Generate Decode
Standard QR (versions 1–40) ISO/IEC 18004 ✅ ✅
Micro QR (M1–M4) ISO/IEC 18004 ✅ ✅
rMQR (R7x43–R17x139) ISO/IEC 23941 ✅ ✅
  • Designed for speed and minimal memory allocation
  • Get the dark modules as rectangles for your own renderer, or write SVG, small 1-bit PNG, raw pixels, and terminal text without additional dependencies.
  • Render styled PNG, JPEG, WebP, and SVG images with gradients, shapes, and icons through SkiaSharp.
  • Decode module matrices, pixels, image files, and streams, including every symbol in one image.
  • Encode GS1 QR Codes, GS1 Digital Link URIs, binary data with any ECI, and Japanese text in Kanji mode.
  • Run on Windows, Linux, macOS, iOS, Android, and WebAssembly.

Installation

Package What
FeatherQR Generates and decodes all three symbologies. Writes SVG, PNG, raw pixels, and terminal text.
FeatherQR.SkiaSharp Renders styled images (shapes, gradients, icons, JPEG, WebP) and decodes image files with SkiaSharp.
FeatherQR.Gs1 Generates and reads GS1 QR Codes and GS1 Digital Link URIs.
SkiaSharp.QrCode Empty package that depends on FeatherQR.SkiaSharp, for upgrading existing projects.
dotnet add package FeatherQR

# Styled images or image file decoding
dotnet add package FeatherQR.SkiaSharp

# GS1 data
dotnet add package FeatherQR.Gs1

FeatherQR.SkiaSharp needs SkiaSharp native assets on Linux, with NativeAOT, and in WebAssembly. See SkiaSharp native assets.

Important

2.0.0 renames SkiaSharp.QrCode to FeatherQR and SkiaSharp.QrCode.Image to FeatherQR.SkiaSharp, with new namespaces. See the Migration Guide.

Quick Start

The Playground runs FeatherQR in your browser. It styles, downloads, shares, and decodes symbols.

With FeatherQR:

using FeatherQR;

var qr = QRCodeGenerator.Create("https://example.com", QREccLevel.M);
File.WriteAllBytes("qrcode.png", SymbolImageWriter.GetPngBytes(qr));
File.WriteAllText("qrcode.svg", SymbolImageWriter.GetSvgString(qr));

if (QRCodeDecoder.TryDecode(qr, out var text))
    Console.WriteLine(text);

With FeatherQR.SkiaSharp:

using SkiaSharp;
using FeatherQR;
using FeatherQR.SkiaSharp;

File.WriteAllBytes("qrcode.png", QRCodeImageBuilder.GetPngBytes("https://example.com"));

using var bitmap = SKBitmap.Decode("qrcode.png");
if (QRCodeDecoder.TryDecode(bitmap, out var text))
    Console.WriteLine(text);

The examples below use .NET 10, C# 14, implicit usings, and the three using directives above. Replace file names such as logo.png with your own.

API Overview

FeatherQR generates and decodes symbols and writes plain images.

What Standard QR Micro QR rMQR
Generate a symbol QRCodeGenerator MicroQRCodeGenerator RmQRCodeGenerator
Generated symbol QRCodeData MicroQRCodeData RmQRCodeData
Get dark modules as rectangles GetModuleRectangles GetModuleRectangles GetModuleRectangles
Write SVG, PNG, raw pixels, or terminal text SymbolImageWriter SymbolImageWriter SymbolImageWriter
Decode a symbol, matrix, or grayscale pixels QRCodeDecoder MicroQRCodeDecoder RmQRCodeDecoder
Decode all symbol types from grayscale pixels SymbolDecoder SymbolDecoder SymbolDecoder
Convert pixels to grayscale for decoding LuminanceConverter LuminanceConverter LuminanceConverter

FeatherQR.SkiaSharp adds gradients, custom shapes, icons drawn into raster images, JPEG and WebP output, drawing to an SKCanvas, and decoding from SKBitmap objects and image files.

What Standard QR Micro QR rMQR
Create styled PNG, JPEG, WebP, or SVG QRCodeImageBuilder MicroQRCodeImageBuilder RmQRCodeImageBuilder
Render a symbol to SKCanvas SymbolRenderer SymbolRenderer SymbolRenderer
Decode an SKBitmap or an image file QRCodeDecoder MicroQRCodeDecoder RmQRCodeDecoder
Decode all symbol types from an SKBitmap or an image file SymbolDecoder SymbolDecoder SymbolDecoder

The same task in each package, where options is a SymbolImageOptions and builder is a QRCodeImageBuilder:

What FeatherQR FeatherQR.SkiaSharp
Size, equal modules Width = 512, Height = 512 .WithSize(512, 512)
Size, filled Width = 512, Height = 512, FillCanvas = true .WithSize(512, 512).WithFillCanvas()
Modules ModuleStyle = ModuleStyle.Circle, ModuleScalePercent = 92 .WithModuleShape(CircleModuleShape.Default, sizePercent: 0.92f)
Finder patterns FinderPatternStyle = FinderPatternStyle.Circle .WithFinderPatternShape(CircleFinderPatternShape.Default)
Rounded finder patterns FinderPatternStyle = FinderPatternStyle.RoundedSquare, FinderPatternCornerRadiusPercent = 30 .WithFinderPatternShape(new RoundedRectangleFinderPatternShape(0.3f))
Colors DarkColor = new SymbolColor(30, 58, 138), LightColor = new SymbolColor(255, 255, 255, 0) .WithColors(new SKColor(30, 58, 138), SKColors.Transparent)
Icon IconSizeModules = 7, IconImage = File.ReadAllBytes("logo.png") (SVG embeds it) .WithIcon(IconData.FromImage(logo, IconSize.Modules(7)))
PNG SymbolImageWriter.GetPngBytes(qr, options) builder.ToByteArray()
SVG SymbolImageWriter.GetSvgString(qr, options) builder.ToSvgString()
Stream stream.Write(SymbolImageWriter.GetPngBytes(qr, options)) builder.SaveTo(stream)
Stream, async await stream.WriteAsync(SymbolImageWriter.GetPngBytes(qr, options)) await builder.SaveToAsync(stream)
Buffer writer SymbolImageWriter.WritePng(qr, bufferWriter, options) builder.SaveTo(bufferWriter)
Raw pixels SymbolImageWriter.TryWritePixels(qr, buffer, PixelLayout.Rgba8888, premultipliedAlpha: false, out var width, out var height, options) builder.ToBitmap()
Read an image QRCodeDecoder.TryDecodeImage(gray, width, height, out string text, out _) QRCodeDecoder.TryDecode(bitmap, out string text)

With default colors and square modules, both give the same pixels for the same size. Without a size, the core writes 8 pixels per module and the builders write 512 × 512. For small PNG files, use the core. It writes a plain symbol in 1 bit per pixel and a styled symbol in 4, and FeatherQR.SkiaSharp writes 8-bit RGB.

Generate

Error Correction

The error correction level sets how much of a damaged or covered symbol a reader can recover.

Level Recovers Use for
L About 7% Clean environments, maximum capacity
M About 15% General purpose
Q About 25% Outdoor use, some damage expected
H About 30% Icons, custom module shapes, harsh environments
var qr = QRCodeGenerator.Create("https://example.com", QREccLevel.M);

// M as the minimum: the highest level that fits without a larger symbol
var boosted = QRCodeGenerator.Create("https://example.com", QREccLevel.M, new QRCodeGeneratorOptions { BoostEccLevel = true });
Console.WriteLine(boosted.EccLevel); // Q, at the same version

// The builders take the same arguments
var png = new QRCodeImageBuilder("https://example.com", QREccLevel.M, new QRCodeGeneratorOptions { BoostEccLevel = true }).ToByteArray();

Default square modules scan best. Circles, rounded squares, and smaller modules cause more scan errors, and icons cover symbol data. Use H, or boosting, with any of them.

Generator Options

var options = new QRCodeGeneratorOptions { EciMode = EciMode.Utf8, QuietZoneSize = 0 };
var qr = QRCodeGenerator.Create("content", QREccLevel.M, options);
var pinned = QRCodeGenerator.Create("content", QREccLevel.M, options with { Version = 20 });

var rmqr = RmQRCodeGenerator.Create("content", RmQREccLevel.M, new RmQRCodeGeneratorOptions
{
    Height = RmQRHeight.H9,
    Segmentation = RmQRSegmentation.Single, // Prefer speed over symbol size
});

The defaults of each option. The default quiet zones, in modules, follow the standards.

Option QRCodeGeneratorOptions MicroQRCodeGeneratorOptions RmQRCodeGeneratorOptions
EciMode Default (auto-detect) — Default (auto-detect)
Utf8Bom false — —
Version Any (1-40) Any (M1-M4) null (fit automatically)
QuietZoneSize 4 2 2
BoostEccLevel false — —
MaskPattern null (automatic, 0-7) null (automatic, 0-3) —
FitStrategy — — MinimizeArea
Height — — null (any height)
Segmentation Optimal Optimal Optimal
Fnc1 None — None
AllowKanji false false false

Version and Mask

Version 1 is 21 × 21 modules, and each version adds 4 modules per side, up to 177 × 177 at version 40. The generator selects the smallest version that fits. Data Capacity lists what each version holds.

var exact = new QRCodeGeneratorOptions { Version = 15 };                           // exactly version 15
var range = new QRCodeGeneratorOptions { Version = new(10, 20) };                  // 10 to 20, inclusive
var minimum = new QRCodeGeneratorOptions { Version = QRVersionRange.AtLeast(10) }; // 10 or larger
var micro = new MicroQRCodeGeneratorOptions { Version = MicroQRVersion.M4 };       // Micro QR takes a version or a range too
var rmqr = new RmQRCodeGeneratorOptions { Version = RmQRVersion.R11x43 };          // rMQR takes a version, or Height and FitStrategy

// false when no version in the range fits. Create throws in that case.
if (QRCodeGenerator.TryGetRequiredBufferSize("content", QREccLevel.M, out var size, range))
    Console.WriteLine(size.Version); // 10

The generator applies the mask pattern that scores best. Set MaskPattern to fix it, or to test a scanner with each pattern. rMQR has one fixed mask.

using var bitmap = SKBitmap.Decode("qr.png");
if (QRCodeDecoder.TryDecode(bitmap, out var text, out var info))
{
    // The same content with the version, level, and mask that the decoder read
    var again = QRCodeGenerator.Create(text, info.EccLevel, new QRCodeGeneratorOptions { Version = info.Version, MaskPattern = info.MaskPattern });
    Console.WriteLine($"version {again.Version}, ECC {again.EccLevel}, mask {again.MaskPattern}");
}

Mixed-Mode Segmentation

The default Optimal splits the content into Numeric, Alphanumeric, and Byte segments to use the fewest bits. Single encodes all content in one mode. Micro QR and rMQR have the same option as MicroQRSegmentation and RmQRSegmentation.

const string content = "https://example.com/item?id=123456789012345678901234567890";

var optimal = QRCodeGenerator.Create(content, QREccLevel.M);
Console.WriteLine(optimal.Version); // 3: Byte + Numeric

var single = QRCodeGenerator.Create(content, QREccLevel.M, new QRCodeGeneratorOptions { Segmentation = QRSegmentation.Single });
Console.WriteLine(single.Version);  // 4: one Byte segment

Encoding Modes

The generator selects the mode of each segment.

Mode Characters Bits per character
Numeric 0–9 About 3.3
Alphanumeric 0–9, A–Z, space, $ % * + - . / : About 5.5
Byte ISO-8859-1 or UTF-8 8 per byte
Kanji JIS X 0208, with AllowKanji 13

For another encoding, encode the text yourself and name the encoding with its ECI assignment.

using System.Text;

Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
var latin2 = Encoding.GetEncoding("iso-8859-2");
var qr = QRCodeGenerator.Create(latin2.GetBytes("Łódź"), QREccLevel.M, eciAssignment: 4); // 4 is ISO-8859-2, 20 is Shift JIS

// The decoders read ISO-8859-1, UTF-8, and Shift JIS as text. Read other encodings as bytes.
if (!QRCodeDecoder.TryDecode(qr, out var text, out var info)
    && info is { Status: DecodeStatus.UnsupportedContent, EciAssignment: 4 }
    && QRCodeDecoder.TryDecodeBytes(qr, out var bytes, out _))
{
    text = latin2.GetString(bytes);
}

Kanji Mode for Japanese Text

By default, the generators write Japanese text as UTF-8 in Byte mode. With AllowKanji, text in JIS X 0208 uses Kanji mode, which holds about 1.85 times as many characters.

var kanji = new QRCodeGeneratorOptions { AllowKanji = true };

QRCodeGenerator.Create("日本語のテキスト", QREccLevel.M);        // UTF-8, version 2
QRCodeGenerator.Create("日本語のテキスト", QREccLevel.M, kanji); // Kanji, version 1
QRCodeGenerator.Create("東京タワー333m", QREccLevel.M, kanji);   // Kanji and ASCII segments, version 1
MicroQRCodeGenerator.Create("こんにちは", MicroQREccLevel.L, new MicroQRCodeGeneratorOptions { AllowKanji = true }); // M3, where UTF-8 needs M4

Kanji mode is off by default because some readers cannot read it. In tests, the QR scanner of an Android 17 phone and Google Lens could not read it. The iPhone camera and the dedicated readers tested could.

Even with AllowKanji, the text stays UTF-8 in these cases:

  • A character is outside JIS X 0208, such as an emoji, ①, or halfwidth katakana.
  • A character is one of the seven that Windows (CP932) reads differently, such as the wave dash 〜.
  • You set EciMode to a charset, or set Utf8Bom.
  • Single segmentation is set and the text mixes Japanese with ASCII.

Binary Data

byte[] payload = [0x00, 0x01, 0x7F, 0x80, 0xFF];
var qr = QRCodeGenerator.Create(payload, QREccLevel.M);                           // no ECI header, usual for binary data
var declared = QRCodeGenerator.Create(payload, QREccLevel.M, eciAssignment: 899); // 0 to 999999. 899 declares binary data
var rmqr = RmQRCodeGenerator.Create(payload, RmQREccLevel.M, eciAssignment: 899);
var micro = MicroQRCodeGenerator.Create(payload, MicroQREccLevel.L);              // Micro QR has no ECI

if (QRCodeDecoder.TryDecodeBytes(declared, out var bytes, out var info))
    Console.WriteLine($"{bytes.Length} bytes, ECI {info.EciAssignment?.ToString() ?? "none"}"); // 5 bytes, ECI 899

// From an image. For grayscale pixels, use TryDecodeImageBytes.
using var bitmap = SKBitmap.Decode("qr.png");
if (QRCodeDecoder.TryDecodeBytes(bitmap, out var imageBytes, out _))
    File.WriteAllBytes("payload.bin", imageBytes);
  • Byte segments decode unchanged, digits and letters as ASCII, and Kanji as Shift JIS byte pairs.
  • The text-only options EciMode, Utf8Bom, AllowKanji, and Fnc1 throw with byte input.

Note

Phone cameras may not show binary data. In tests, an iPhone camera found a binary symbol but showed no content, and a QR reader app could not read it. Both happened with and without ECI 899. Use binary data with readers your app controls. For other readers, encode the data as text. Base45 in Alphanumeric mode adds about 3% to the raw bytes, and Base64 in Byte mode adds 33%.

Structured Append: One Message Across Several Symbols

CreateStructuredAppend splits one message across up to 16 Standard QR symbols. It uses the fewest symbols in the version range, all at one version.

var longText = string.Concat(Enumerable.Repeat("One message across several symbols. ", 25));
var symbols = QRCodeGenerator.CreateStructuredAppend(longText, QREccLevel.M, new QRCodeGeneratorOptions { Version = QRVersionRange.AtMost(10) });
for (var i = 0; i < symbols.Length; i++)
    File.WriteAllBytes($"part{i}.png", SymbolImageWriter.GetPngBytes(symbols[i]));

// Join the parts. Count and Parity identify the message, and Index gives the order.
var parts = new List<(QRStructuredAppend Header, string Text)>();
foreach (var symbol in symbols)
{
    if (QRCodeDecoder.TryDecode(symbol, out var part, out var info) && !info.StructuredAppend.IsEmpty)
        parts.Add((info.StructuredAppend, part));
}
foreach (var message in parts.GroupBy(p => (p.Header.Count, p.Header.Parity)))
{
    var ordered = message.OrderBy(p => p.Header.Index).ToArray();
    if (ordered.Select(p => p.Header.Index).SequenceEqual(Enumerable.Range(0, message.Key.Count))) // every part, once
        Console.WriteLine(string.Concat(ordered.Select(p => p.Text)));
}

Text that fits in one symbol gives one plain symbol, and its StructuredAppend.IsEmpty is true. For bytes, decode with TryDecodeBytes and join the bytes in the same order.

GS1 Data

Carrier Used for Method
QR Code with a GS1 Digital Link URI Retail point of sale CreateGs1DigitalLink
GS1 QR Code (FNC1 in first position) Healthcare, logistics, assets, and other uses away from the point of sale CreateGs1
using FeatherQR.Gs1;

// GS1 QR Code. The generator places the separators and sets FNC1.
var gs1 = QRCodeGenerator.CreateGs1("(01)09520123456788(17)251231(10)ABC123", QREccLevel.M);

// https://id.gs1.org/01/09520123456788/10/ABC123?17=251231
var link = QRCodeGenerator.CreateGs1DigitalLink("(01)09520123456788(17)251231(10)ABC123", QREccLevel.M);

// Your own domain: https://brand.example/01/09520123456788
var branded = QRCodeGenerator.CreateGs1DigitalLink("(01)09520123456788", QREccLevel.M, stem: "https://brand.example");

// rMQR
var rmqr = RmQRCodeGenerator.CreateGs1("(01)09520123456788", RmQREccLevel.M);

// (AI) text from a decoded symbol of either carrier. TryRead checks only the structure, not the check digit.
if (QRCodeDecoder.TryDecode(gs1, out var text, out var info) && Gs1ElementString.TryRead(text, info.Fnc1, out var read, out _))
    Console.WriteLine(read); // (01)09520123456788(17)251231(10)ABC123

try
{
    QRCodeGenerator.CreateGs1("(01)09520123456789", QREccLevel.M);
}
catch (Gs1FormatException ex)
{
    Console.WriteLine($"{ex.Error.Kind} at {ex.Error.Offset}"); // InvalidCheckDigit at 17
}

Input that starts with ( is (AI) text. Other input is an element string, with U+001D after each variable-length value. Gs1ElementString checks and converts GS1 data without a symbol.

using FeatherQR.Gs1;

// TryValidate checks lengths, characters, check digits, dates, and AI combinations
if (!Gs1ElementString.TryFromHri("(01)09520123456788(17)251231(10)ABC123", out var element, out var error)
    || !Gs1ElementString.TryValidate(element, out error))
{
    Console.WriteLine($"{error.Kind} at {error.Offset}");
    return;
}

Gs1ElementString.TryToHri(element, out var hri, out _);
Gs1ElementString.TryToDigitalLink(element, out var uri, out _);
Gs1ElementString.TryFromDigitalLink(uri, out var fromUri, out _);

foreach (var item in Gs1ElementString.EnumerateElements(element))
    Console.WriteLine($"{item.Ai} = {item.Value}"); // the first line is 01 = 09520123456788

// The conversions have span overloads that do not allocate
Span<char> buffer = stackalloc char[128];
if (Gs1ElementString.TryToHri(element, buffer, out var charsWritten, out _))
    Console.Out.WriteLine(buffer[..charsWritten]);

Note

  • Leave EciMode at its default. GS1 QR Code does not support ECI.
  • The default Standard QR quiet zone of 4 modules meets the GS1 requirement.
  • GS1 General Specifications Release 26.0 does not list rMQR as a carrier, so a GS1 scanner may not accept it. GS1 excludes Micro QR, which has no FNC1 mode.
  • The AI table comes from the GS1 Barcode Syntax Dictionary release in Gs1ElementString.DictionaryRelease. Newer AIs fail with UnknownAi until a package update includes them.

Zero-Allocation APIs

The generators and decoders of all three symbologies have span overloads.

using System.Buffers;

// false when the content does not fit. Invalid arguments throw. Pass the same options to both calls.
if (!QRCodeGenerator.TryGetRequiredBufferSize("content", QREccLevel.M, out var size))
    return;

var modules = ArrayPool<byte>.Shared.Rent(size.BufferSize);
var chars = ArrayPool<char>.Shared.Rent(QRCodeDecoder.GetMaxDecodedLength(size.Version));
try
{
    // One byte per module, row by row, with the quiet zone. 0 is light, and any other value is dark.
    var written = QRCodeGenerator.Create("content", QREccLevel.M, modules);
    var matrix = modules.AsSpan(0, written);
    var firstFinderModuleIsDark = matrix[4 * size.Size + 4] != 0; // row 4, column 4

    if (QRCodeDecoder.TryDecode(matrix, size.Size, chars, out var charsWritten, out _))
        Console.Out.WriteLine(chars.AsSpan(0, charsWritten));
}
finally
{
    ArrayPool<byte>.Shared.Return(modules);
    ArrayPool<char>.Shared.Return(chars);
}

For rMQR, pass the resolved version back to skip version selection.

if (RmQRCodeGenerator.TryGetRequiredBufferSize("content", RmQREccLevel.M, out var size))
{
    Span<byte> modules = stackalloc byte[size.BufferSize]; // at most 143 x 21 with the default quiet zone
    RmQRCodeGenerator.Create("content", RmQREccLevel.M, modules, new RmQRCodeGeneratorOptions { Version = size.Version });
}

Draw and Write Images

samples/ConsoleAppCore and samples/ConsoleApp make the images in this section.

Module Rectangles for Your Renderer

GetModuleRectangles returns the dark modules as merged rectangles. Draw them directly with a GPU or a graphics API, with no image to encode or upload. The coordinates are in modules, include the quiet zone, and match the qr[row, col] indexer. The rectangles do not overlap, so a translucent color stays even.

var qr = QRCodeGenerator.Create("https://example.com", QREccLevel.M);

const float scale = 8; // pixels per module
foreach (var r in qr.GetModuleRectangles())
    batch.AddQuad(r.X * scale, r.Y * scale, r.Width * scale, r.Height * scale); // your sprite batch or vertex buffer

If you anti-alias each rectangle separately, a faint seam shows where two rectangles meet inside a pixel. Fill them as one path, or align the edges to whole pixels. See ToDrawingImage in samples/Dotfiles/Wpf.cs.

To style the modules, draw the finder patterns separately and keep them solid, because readers find the symbol by them.

var qr = QRCodeGenerator.Create("https://example.com", QREccLevel.M);
ModuleRect[] finders = [qr.GetFinderPatternRectangle(0), qr.GetFinderPatternRectangle(1), qr.GetFinderPatternRectangle(2)]; // top-left, top-right, bottom-left

const float scale = 8;
foreach (var r in qr.GetModuleRectangles())
{
    // In a generated symbol, no rectangle crosses a finder pattern's edge
    if (Array.Exists(finders, f => r.X >= f.X && r.X < f.X + f.Width && r.Y >= f.Y && r.Y < f.Y + f.Height))
        continue;
    batch.AddRoundQuad(r.X * scale, r.Y * scale, r.Width * scale, r.Height * scale); // your styled module
}
foreach (var f in finders)
    batch.AddFinder(f.X * scale, f.Y * scale, f.Width * scale); // your finder pattern, 7 x 7 modules

Micro QR and rMQR symbols have one finder pattern, and rMQR symbols have Width and Height instead of Size.

var rmqr = RmQRCodeGenerator.Create("https://example.com", RmQREccLevel.M);
var finder = rmqr.GetFinderPatternRectangle();
var (widthInModules, heightInModules) = (rmqr.Width, rmqr.Height);

To avoid allocation, rent the buffer.

using System.Buffers;

var qr = QRCodeGenerator.Create("https://example.com", QREccLevel.M);
var rects = ArrayPool<ModuleRect>.Shared.Rent(qr.GetModuleRectanglesMaxCount());
if (qr.TryGetModuleRectangles(rects, out var count))
{
    foreach (var r in rects.AsSpan(0, count))
        batch.AddQuad(r.X, r.Y, r.Width, r.Height);
}
ArrayPool<ModuleRect>.Shared.Return(rects);

Plain Images with FeatherQR

SymbolImageWriter writes SVG, PNG, raw pixels, and terminal text from any symbol with only the core package. A symbol gives the same bytes on every target framework.

var qr = QRCodeGenerator.Create("https://example.com", QREccLevel.M);
File.WriteAllText("qrcode.svg", SymbolImageWriter.GetSvgString(qr));
File.WriteAllBytes("qrcode.png", SymbolImageWriter.GetPngBytes(qr));

// Without the quiet zone
var bare = QRCodeGenerator.Create("https://example.com", QREccLevel.M, new QRCodeGeneratorOptions { QuietZoneSize = 0 });
File.WriteAllBytes("bare.png", SymbolImageWriter.GetPngBytes(bare));

Image Size

var qr = QRCodeGenerator.Create("https://example.com", QREccLevel.M);

// 10 pixels per module. The default is 8.
var png10 = SymbolImageWriter.GetPngBytes(qr, new SymbolImageOptions { ModulePixelSize = 10 });

// Exactly 512 x 512: equal whole-pixel modules, the symbol centered, the rest light
var png512 = SymbolImageWriter.GetPngBytes(qr, new SymbolImageOptions { Width = 512, Height = 512 });

// The symbol fills the image. Neighboring modules can differ by one pixel.
var filled = SymbolImageWriter.GetPngBytes(qr, new SymbolImageOptions { Width = 512, Height = 512, FillCanvas = true });

// The height follows the aspect ratio
var svg300 = SymbolImageWriter.GetSvgString(qr, new SymbolImageOptions { Width = 300 });

// Where the symbol is in the image, without the quiet zone, in pixels
var options = new SymbolImageOptions { Width = 400, Height = 300 };
var (x, y, width, height) = SymbolImageWriter.GetSymbolRectangle(qr, options);

Use FillCanvas when the symbol must fill a fixed area. Without it, dense symbols can be smaller. In 512 × 512, version 10 fills 89% of each side and version 40 fills 72%.

Colors, Styles, and Icons

SymbolImageOptions Default Effect
DarkColor, LightColor Black, white Colors with alpha. A fully transparent LightColor leaves out the background.
ModuleStyle Square Square, Circle, or RoundedSquare modules
ModuleScalePercent 100 Size of each module in its cell, 50 to 100
ModuleCornerRadiusPercent 30 Corner radius of RoundedSquare modules
FinderPatternStyle Square Square, Circle, RoundedSquare, or RoundedSquareCircle finder patterns
FinderPatternCornerRadiusPercent 30 Corner radius of the rounded finder patterns
IconSizeModules 0 Side of the light square kept free for an icon. Standard QR only.
IconBorderModules 1 Light border around the icon
IconImage, IconMediaType Empty, image/png Encoded image that SVG output embeds
MaxCoreOccupancyPercent 30 Largest side of the icon with its border, as a share of the symbol without the quiet zone. A larger icon throws, and so does one that reaches a finder pattern.
var transparent = new SymbolImageOptions
{
    DarkColor = new SymbolColor(0x1E, 0x3A, 0x8A),
    LightColor = new SymbolColor(0, 0, 0, 0),
};

var styled = new SymbolImageOptions
{
    ModuleStyle = ModuleStyle.Circle,
    ModuleScalePercent = 90,
    FinderPatternStyle = FinderPatternStyle.RoundedSquareCircle,
    DarkColor = new SymbolColor(0x1E, 0x3A, 0x8A),
};

// Version 5 or larger leaves room for a 7-module icon and its border
var qr = QRCodeGenerator.Create("https://example.com", QREccLevel.H, new QRCodeGeneratorOptions { Version = QRVersionRange.AtLeast(5) });
var icon = new SymbolImageOptions { IconSizeModules = 7, IconImage = File.ReadAllBytes("logo.png") };
var svg = SymbolImageWriter.GetSvgString(qr, icon);                       // embeds the logo
var png = SymbolImageWriter.GetPngBytes(qr, icon);                        // leaves the area light
var (x, y, width, height) = SymbolImageWriter.GetIconRectangle(qr, icon); // where to draw the logo in the PNG, in pixels
Navy modules on a transparent background Circle modules and rounded finder patterns An icon drawn into the pixels where GetIconRectangle points

Raw Pixels, Buffer Writers, and Terminal Text

using System.Buffers;

var qr = QRCodeGenerator.Create("https://example.com", QREccLevel.M);

// Gray8, Rgba8888, Bgra8888, Rgb888x, Bgr888x, Rgb24, or Bgr24
var pixels = new byte[SymbolImageWriter.GetPixelBufferSize(qr, PixelLayout.Bgra8888)];
SymbolImageWriter.TryWritePixels(qr, pixels, PixelLayout.Bgra8888, premultipliedAlpha: false, out var width, out var height);

// A region of a larger RGBA image: start at the region's first pixel and pass the image's row stride
const int canvasWidth = 1000, canvasHeight = 800, left = 40, top = 60;
var canvas = new byte[canvasWidth * canvasHeight * 4];
var (symbolWidth, symbolHeight) = SymbolImageWriter.GetImageSize(qr); // 264 x 264
SymbolImageWriter.TryWritePixels(qr, canvas.AsSpan((top * canvasWidth + left) * 4), rowBytes: canvasWidth * 4, PixelLayout.Rgba8888, premultipliedAlpha: false, out _, out _);

// Buffer writers, without allocation after warmup
var writer = new ArrayBufferWriter<byte>();
SymbolImageWriter.WritePng(qr, writer);
writer.ResetWrittenCount();
SymbolImageWriter.WriteSvg(qr, writer);

// Terminal text, two module rows per line
Console.OutputEncoding = System.Text.Encoding.UTF8;                 // a CJK code page prints some half blocks as ?
Console.Write(SymbolImageWriter.GetTerminalText(qr));               // for a light terminal
Console.Write(SymbolImageWriter.GetTerminalText(qr, invert: true)); // for a dark terminal

Styled Images with FeatherQR.SkiaSharp

QRCodeImageBuilder, MicroQRCodeImageBuilder, and RmQRCodeImageBuilder have the same methods, but only Standard QR supports icons.

Goal API Notes
An exact module size WithModulePixelSize(n) Output side = symbol size in modules × n
An exact module size in a larger canvas WithModulePixelSize(n) + WithSize(w, h) A canvas smaller than the symbol throws.
A fixed image size WithSize(w, h) Equal whole-pixel modules, the symbol centered
A fixed image size that the symbol fills WithSize(w, h) + WithFillCanvas() Neighboring modules can differ by one pixel.

Give each module enough pixels. On clean images, FeatherQR's decoder starts to fail below about 1.5 pixels per module, and phone cameras need more.

var colors = new QRCodeImageBuilder("https://example.com")
    .WithModulePixelSize(16)
    .WithSize(800, 800)
    .WithColors(codeColor: SKColor.Parse("#000080"), backgroundColor: SKColor.Parse("#FFE4B5"))
    .WithClearColor(SKColors.Transparent) // outside the symbol. The default is the background color.
    .ToByteArray();

var circles = new QRCodeImageBuilder("https://example.com")
    .WithModuleShape(CircleModuleShape.Default, sizePercent: 0.95f)
    .WithCodeColor(SKColors.DarkBlue)
    .ToByteArray();

var roundedFinders = new QRCodeImageBuilder("https://example.com")
    .WithFinderPatternShape(RoundedRectangleFinderPatternShape.Default)
    .ToByteArray();
Navy modules on a moccasin background Circle modules Rounded finder patterns

Gradients and Icons

var gradient = new QRCodeImageBuilder("https://example.com", QREccLevel.H)
    .WithGradient(new GradientOptions([SKColors.Blue, SKColors.Purple, SKColors.Pink], GradientDirection.TopLeftToBottomRight, [0f, 0.5f, 1f]))
    .WithModuleShape(RoundedRectangleModuleShape.Default, sizePercent: 0.9f)
    .ToByteArray();

// An icon sized in modules sits on the grid. Version 5 fits 7 modules and a 2-module border inside the default 30% limit.
using var logo = SKBitmap.Decode(File.ReadAllBytes("logo.png"));
var withLogo = new QRCodeImageBuilder("https://example.com", QREccLevel.H, new QRCodeGeneratorOptions { Version = 5 })
    .WithModulePixelSize(12)
    .WithColors(codeColor: SKColors.DarkGreen, backgroundColor: SKColors.LightYellow)
    .WithIcon(IconData.FromImage(logo, IconSize.Modules(7, border: 2)))
    .ToByteArray();

// Size the icon by percent and pixels instead
var byPercent = IconData.FromImage(logo, IconSize.Percent(15, borderPixels: 10));

// Text below the icon
using var font = new SKFont { Size = 18, Typeface = SKTypeface.FromFamilyName("sans-serif", SKFontStyle.Bold) };
var withText = new IconData
{
    Icon = new ImageTextIconShape(logo, "FooBar", SKColors.Black, font, textPadding: 2),
    Size = IconSize.Percent(13, borderPixels: 18),
};
Gradient from blue to pink A logo in the center

Image Formats

var builder = new QRCodeImageBuilder("https://example.com");
byte[] png = builder.ToByteArray();
string svg = builder.ToSvgString(); // every styling option applies, and the size is the viewport
byte[] jpeg = builder.WithFormat(SKEncodedImageFormat.Jpeg, quality: 90).ToByteArray();
byte[] webp = builder.WithFormat(SKEncodedImageFormat.Webp, quality: 80).ToByteArray();

Drawing into Your Own SKCanvas

SymbolRenderer draws a symbol of any type on an existing SKCanvas.

var qr = QRCodeGenerator.Create("content", QREccLevel.M);
using var surface = SKSurface.Create(new SKImageInfo(400, 400));

// Centers the symbol in the area and fills the rest of the area with the background
SymbolRenderer.Render(surface.Canvas, SKRect.Create(50, 50, 300, 300), qr, SKColors.Black, SKColors.White);

Pattern 15 in samples/ConsoleApp draws a symbol in a card with text.

A symbol in a card with text below it

System.Drawing, WPF, and ImageSharp

Choose the PixelLayout by the byte order in memory. A format's name does not always show it.

Library Pixel format PixelLayout
System.Drawing Format32bppArgb Bgra8888
System.Drawing Format32bppPArgb Bgra8888, premultiplied
System.Drawing Format32bppRgb Bgr888x
System.Drawing Format24bppRgb Bgr24
WPF PixelFormats.Bgra32 Bgra8888
WPF PixelFormats.Pbgra32 Bgra8888, premultiplied
WPF PixelFormats.Bgr32 Bgr888x
WPF PixelFormats.Bgr24, PixelFormats.Rgb24 Bgr24, Rgb24
ImageSharp Rgba32, Bgra32 Rgba8888, Bgra8888
ImageSharp Rgb24, Bgr24 Rgb24, Bgr24
  • For a premultiplied format, pass premultipliedAlpha: true to both TryWritePixels and LuminanceConverter.Convert.
  • A 24-bit row is often padded to a multiple of four bytes. Pass the row stride that the library reports, not width × 3.
  • The fourth byte of Format32bppRgb and Bgr32 is not alpha, and files from other tools may hold 0 there. Read as Bgra8888, a 0 is a transparent pixel and the image turns white. Use Bgr888x.

For example, with WPF:

using System.Windows.Media;
using System.Windows.Media.Imaging;

// Write a symbol into a BitmapSource
var qr = QRCodeGenerator.Create("https://example.com", QREccLevel.M);
var pixels = new byte[SymbolImageWriter.GetPixelBufferSize(qr, PixelLayout.Bgra8888)];
SymbolImageWriter.TryWritePixels(qr, pixels, PixelLayout.Bgra8888, premultipliedAlpha: false, out var width, out var height);
BitmapSource bitmap = BitmapSource.Create(width, height, 96, 96, PixelFormats.Bgra32, null, pixels, width * 4);

// Read any BitmapSource
var bgra = new FormatConvertedBitmap(bitmap, PixelFormats.Bgra32, null, 0);
var (w, h) = (bgra.PixelWidth, bgra.PixelHeight);
var source = new byte[w * h * 4];
bgra.CopyPixels(source, w * 4, 0);
var luminance = new byte[w * h];
LuminanceConverter.Convert(source, w, h, w * 4, PixelLayout.Bgra8888, premultipliedAlpha: false, luminance);
if (QRCodeDecoder.TryDecodeImage(luminance, w, h, out string text, out _))
    Console.WriteLine(text);

Full samples: System.Drawing, WPF, and ImageSharp. ImageSharp 3.2.0 and later need a Six Labors license key for Release builds.

Decoders

The decoders read module matrices, screenshots, generated images, scans, and camera photos. They handle rotated, mirrored, and tilted symbols, gradual shading, and soft-edged shadows. Glare, damage, blur, curved surfaces, steep angles, and strong lens distortion make reads less reliable.

// A generated symbol
var qr = QRCodeGenerator.Create("https://example.com", QREccLevel.M);
if (QRCodeDecoder.TryDecode(qr, out var text))
    Console.WriteLine(text);

// An image file, with FeatherQR.SkiaSharp
using var bitmap = SKBitmap.Decode("qr.png");
if (QRCodeDecoder.TryDecode(bitmap, out text, out var info))
{
    Console.WriteLine($"{text} (version {info.Version}, ECC {info.EccLevel}, {info.ErrorsCorrected} errors corrected)");

    // The corners without the quiet zone, in pixels. TopLeft is at the symbol's own top-left, wherever that is in the image.
    var corners = info.Corners; // TopLeft, TopRight, BottomRight, BottomLeft
    Console.WriteLine($"({corners.TopLeft.X}, {corners.TopLeft.Y})");
}
else
{
    Console.WriteLine(info.Status switch
    {
        DecodeStatus.NotDetected => "no symbol found",
        DecodeStatus.DataUncorrectable => "found, but too damaged",
        DecodeStatus.UnsupportedContent => $"read, but in an unsupported encoding (ECI {info.EciAssignment}). Use TryDecodeBytes.",
        var other => other.ToString(),
    });
}

// C# 13 or earlier. Also MicroQRCodeDecoderExtensions, RmQRCodeDecoderExtensions, and SymbolDecoderExtensions.
QRCodeDecoderExtensions.TryDecode(bitmap, out text);

A symbol or a matrix has no corners, and Corners.IsEmpty is true. samples/Dotfiles/DecodeCorners.cs draws the outlines over sample images.

Pixels from any other source go through LuminanceConverter, which puts transparent pixels on white.

// RGBA. rowBytes is the row stride.
static bool ReadRgba(byte[] rgba, int width, int height, int rowBytes, out string text)
{
    var luminance = new byte[width * height];
    LuminanceConverter.Convert(rgba, width, height, rowBytes, PixelLayout.Rgba8888, premultipliedAlpha: false, luminance);
    return QRCodeDecoder.TryDecodeImage(luminance, width, height, out text, out _);
}

// A camera frame in NV12, NV21, or I420. The Y plane is the luminance.
static bool ReadYPlane(byte[] y, int width, int height, int rowBytes, out string text)
{
    var luminance = new byte[width * height];
    LuminanceConverter.Convert(y, width, height, rowBytes, PixelLayout.Gray8, premultipliedAlpha: false, luminance);
    return QRCodeDecoder.TryDecodeImage(luminance, width, height, out text, out _);
}

Several Symbols in One Image

Each method returns every decodable symbol once and skips symbols inside a decoded symbol.

using var sheet = SKBitmap.Decode("sheet.jpg");
foreach (var result in QRCodeDecoder.DecodeSymbols(sheet))
    Console.WriteLine($"{result.Text} at ({result.Info.Corners.TopLeft.X}, {result.Info.Corners.TopLeft.Y})");

// All three symbologies
foreach (var symbol in SymbolDecoder.DecodeSymbols(sheet))
{
    var version = symbol.Symbology switch
    {
        Symbology.StandardQR => symbol.StandardQR.Info.Version.ToString(),
        Symbology.MicroQR => symbol.MicroQR.Info.Version.ToString(),
        _ => symbol.RmQR.Info.Version.ToString(),
    };
    Console.WriteLine($"{symbol.Symbology} {version}: {symbol.Text} at ({symbol.Corners.TopLeft.X}, {symbol.Corners.TopLeft.Y})");
}

With the core package, pass luminance:

static void ReadAll(byte[] luminance, int width, int height)
{
    foreach (var symbol in SymbolDecoder.DecodeImageSymbols(luminance, width, height))
        Console.WriteLine(symbol.Text);

    foreach (var symbol in QRCodeDecoder.DecodeImageSymbolsBytes(luminance, width, height))
        Console.WriteLine(Convert.ToHexString(symbol.Bytes));

    // Stops when the buffer is full
    var results = new QRCodeDecodeResult[4];
    var count = QRCodeDecoder.DecodeImageSymbols(luminance, width, height, results);
}

A search for every symbol takes longer than a decode of one, even with one symbol in the image. Images with many finder patterns of other codes can take several times longer. SymbolDecoder takes longer than one decoder, especially when it finds finder patterns but decodes nothing. Use a single-symbology decoder when you know the type.

Async and Stream I/O

Only methods that do I/O have an async version. These are in FeatherQR.SkiaSharp. The core reads pixels, not image files, so it has no stream overloads.

Task Sync Async
Write an image builder.SaveTo(stream) builder.SaveToAsync(stream)
Write an SVG builder.SaveToSvg(stream) builder.SaveToSvgAsync(stream)
Read one symbol QRCodeDecoder.Decode(stream) QRCodeDecoder.DecodeAsync(stream)
Read every symbol QRCodeDecoder.DecodeSymbols(stream) QRCodeDecoder.DecodeSymbolsAsync(stream)
Read every symbol of all symbologies SymbolDecoder.DecodeSymbols(stream) SymbolDecoder.DecodeSymbolsAsync(stream)

ASP.NET Core disables synchronous I/O on request and response bodies by default. Use the async methods, return the bytes, or write to the response's PipeWriter.

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.MapGet("/qr.png", async (string text, HttpResponse response, CancellationToken cancellationToken) =>
{
    response.ContentType = "image/png";
    await new QRCodeImageBuilder(text).SaveToAsync(response.Body, cancellationToken);
});

app.MapGet("/qr.svg", (string text) =>
    Results.Text(SymbolImageWriter.GetSvgString(QRCodeGenerator.Create(text, QREccLevel.M)), "image/svg+xml"));

// No copy. Cancellation applies only to the flush.
app.MapGet("/qr-pipe.png", async (string text, HttpResponse response, CancellationToken cancellationToken) =>
{
    response.ContentType = "image/png";
    SymbolImageWriter.WritePng(QRCodeGenerator.Create(text, QREccLevel.M), response.BodyWriter);
    await response.BodyWriter.FlushAsync(cancellationToken);
});

app.MapPost("/scan", async (HttpRequest request, CancellationToken cancellationToken) =>
{
    try
    {
        var result = await QRCodeDecoder.DecodeAsync(request.Body, cancellationToken);
        return result.Success
            ? Results.Text(result.Text)
            : Results.Text(result.Info.Status.ToString(), statusCode: StatusCodes.Status422UnprocessableEntity);
    }
    catch (InvalidDataException)
    {
        return Results.BadRequest(); // not an image, or over a limit
    }
});

app.Run();
  • A write renders the whole image first, so a rendering failure leaves the stream unchanged. It does not flush the stream. A canceled write may leave partial output.
  • A read starts at the current position, reads to the end, and leaves the stream open. It does not apply EXIF orientation, so Corners are in the stored orientation.
  • You can change the builder or dispose the icon right after an async call. Keep custom shape objects usable until the task completes.
  • In UI apps, the async methods render and decode on the thread pool. Without a synchronization context, as in ASP.NET Core, the work stays on the calling thread.

A stream read rejects input over 64 MiB, or an image over 16,777,216 pixels (4,096 × 4,096), with InvalidDataException before it allocates pixels. The defaults allow a 12-megapixel photo, but not a 24- or 48-megapixel photo from a recent phone. For larger images, raise the limits. Memory use grows with the pixel count.

// A 200-megapixel photo
var limits = new ImageStreamReadLimits { MaxPixels = 16_384L * 16_384, MaxBytes = 256 * 1024 * 1024 };
await using var photo = File.OpenRead("photo.jpg");
var result = await QRCodeDecoder.DecodeAsync(photo, limits);

Micro QR and rMQR

Micro QR and rMQR have their own generators, image builders, and decoders, with the same shape as the Standard QR ones. See Data Capacity for the versions and their limits.

Micro QR

Micro QR is a smaller square symbol for short data. The generator selects the smallest version from M1 to M4 that fits.

var pngBytes = MicroQRCodeImageBuilder.GetPngBytes("01234567", MicroQREccLevel.L, size: 256);

var styled = new MicroQRCodeImageBuilder("SKU-42", MicroQREccLevel.M)
    .WithModulePixelSize(14)
    .WithColors(codeColor: SKColor.Parse("2D3436"), backgroundColor: SKColors.White)
    .WithModuleShape(RoundedRectangleModuleShape.Default, sizePercent: 0.92f)
    .WithGradient(new GradientOptions([SKColor.Parse("00B894"), SKColor.Parse("0984E3")], GradientDirection.TopLeftToBottomRight))
    .ToByteArray();

var micro = MicroQRCodeGenerator.Create("01234567", MicroQREccLevel.L);
if (MicroQRCodeDecoder.TryDecode(micro, out var text, out var info))
    Console.WriteLine($"{text} ({info.Version}, ECC {info.EccLevel})"); // 01234567 (M2, ECC L)
Micro QR M2 Styled Micro QR with a gradient

rMQR

rMQR is a rectangular symbol for space where a square does not fit well. By default, the generator selects the version with the smallest area.

// size sets the width. The height follows the symbol's aspect ratio.
var pngBytes = RmQRCodeImageBuilder.GetPngBytes("https://example.com/r/12345", RmQREccLevel.M, size: 512);

// A fixed height. The generator selects the width.
var fixedHeight = new RmQRCodeImageBuilder("https://example.com/r/12345", RmQREccLevel.H, new RmQRCodeGeneratorOptions { Height = RmQRHeight.H9 })
    .WithModulePixelSize(12)
    .WithColors(codeColor: SKColor.Parse("2D3436"), backgroundColor: SKColors.White)
    .WithModuleShape(RoundedRectangleModuleShape.Default, sizePercent: 0.9f)
    .ToByteArray();

// MinimizeArea, MinimizeWidth, or MinimizeHeight. They compare modules without the quiet zone.
var flat = RmQRCodeGenerator.Create("012345678901", RmQREccLevel.M, new RmQRCodeGeneratorOptions { FitStrategy = RmQRFitStrategy.MinimizeHeight });
Console.WriteLine(flat.Version); // R7x43

var rmqr = RmQRCodeGenerator.Create("012345678901", RmQREccLevel.M);
if (RmQRCodeDecoder.TryDecode(rmqr, out var text, out var info))
    Console.WriteLine($"{text} ({info.Version}, ECC {info.EccLevel})"); // 012345678901 (R11x27, ECC M)

rMQR R9x139 with a fixed 9-module height

Fit a Frame with the Largest Modules

The version whose aspect ratio is closest to the frame's often gives smaller modules. Find the narrowest version at each height, and take the one with the largest modules.

const string text = "HELLO2026";
int frameWidth = 400, frameHeight = 60;
RmQRVersion? best = null;
var bestModule = 0;
foreach (var height in Enum.GetValues<RmQRHeight>())
{
    var fit = new RmQRCodeGeneratorOptions { Height = height, FitStrategy = RmQRFitStrategy.MinimizeWidth };
    if (!RmQRCodeGenerator.TryGetRequiredBufferSize(text, RmQREccLevel.M, out var size, fit))
        continue; // The text does not fit at this height.
    // size.Width and size.Height include the quiet zone, as the image does.
    // Whole pixels per module, as the image is written. With FillCanvas, divide as double.
    var module = Math.Min(frameWidth / size.Width, frameHeight / size.Height);
    if (module > bestModule)
        (best, bestModule) = (size.Version, module);
}
Console.WriteLine($"{best}, {bestModule} pixels per module"); // R7x59, 5 pixels per module. R17x139, the closest aspect ratio, gets 2.

var rmqr = RmQRCodeGenerator.Create(text, RmQREccLevel.M, new RmQRCodeGeneratorOptions { Version = best });
var png = SymbolImageWriter.GetPngBytes(rmqr, new SymbolImageOptions { Width = frameWidth, Height = frameHeight });

Platforms

SkiaSharp Native Assets

SkiaSharp brings its native assets for Windows, macOS, iOS, and Android by itself. Add a native asset package for Linux, NativeAOT, and WebAssembly.

Linux with font support:

<PackageReference Include="FeatherQR.SkiaSharp" Version="2.0.0-rc.1" />
<PackageReference Include="SkiaSharp.NativeAssets.Linux" Version="4.148.0" />
sudo apt update && sudo apt install -y libfontconfig1

Linux without font dependencies. It can draw text, but cannot use system fonts or find fonts by character.

<PackageReference Include="SkiaSharp.NativeAssets.Linux.NoDependencies" Version="4.148.0" />

NativeAOT on Windows or macOS, for each runtime you publish:

<PackageReference Include="SkiaSharp.NativeAssets.Win32" Version="4.148.0" />
<PackageReference Include="SkiaSharp.NativeAssets.macOS" Version="4.148.0" />

WebAssembly:

<PackageReference Include="SkiaSharp.NativeAssets.WebAssembly" Version="4.148.0" />

NativeAOT and Trimming

FeatherQR publishes without trimming or AOT warnings.

<PropertyGroup>
  <PublishAot>true</PublishAot>
  <InvariantGlobalization>true</InvariantGlobalization>
</PropertyGroup>

On x64, a default NativeAOT build targets CPUs without AVX, so FeatherQR uses its 128-bit SIMD paths. It takes 1.0–2.0 times as long as with the JIT: about 2 times for Standard QR encoding and 1.3–1.5 times for image decoding. If every target machine supports x86-64-v3 (Intel Core since Haswell, AMD since Excavator), enable it. ARM64 needs no setting.

<PropertyGroup>
  <!-- Without AVX2, as on some Pentium, Celeron, and Atom models, the app exits at startup with
       "The required instruction sets are not supported by the current CPU." -->
  <IlcInstructionSet>x86-64-v3</IlcInstructionSet>
</PropertyGroup>

WebAssembly

See samples/BlazorWasm for Blazor, and the Playground source for standalone WebAssembly.

Benchmarks

The benchmarks run on .NET 10 with an AMD Ryzen 9 7950X3D CPU.

Each payload of the corpus:

Encode Performance per payload Decode Performance per payload

Each symbology:

Standard QR Encode Standard QR Decode
Micro QR Encode Micro QR Decode
rMQR Encode rMQR Decode

The same image from each package. The core SymbolImageWriter is faster and allocates less than FeatherQR.SkiaSharp.

Image output by package

License

MIT

FeatherQR.Gs1 includes THIRD-PARTY-NOTICES.md. Its AI table is generated from the Apache-2.0-licensed GS1 Barcode Syntax Dictionary.

About

High-performance QR code generator/reader with renderes support

Topics

Resources

Stars

245 stars

Watchers

1 watching

Forks

Releases

Sponsor this project

Used by

Contributors

Languages