iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
👏

Reading QR Codes from Binary Multi-page TIFFs in .NET Without System.Drawing

に公開

When considering non-Windows environments, System.Drawing cannot be used, so handling TIFFs in such cases requires some consideration.

LibTiff is used for decoding TIFFs. Please refer to the following article for why LibTiff was chosen.

ZXing.Net is used for reading QR codes (and barcodes in general).

While ZXing.Net has bindings for various image processing libraries, unfortunately, there is no binding for LibTiff, so the purpose of this article is to provide one.

Prerequisites

The use of the following environments and libraries is assumed.

  • .NET Framework 4.8.1 or .NET 8.0+
  • BitMiracle.LibTiff.NET 2.4.660+
  • ZXing.Net 0.16.10+

Overview

To create a binding for an image processing library not supported by ZXing.Net, you need to prepare the following two classes:

  • Implementation class of LuminanceSource
  • Implementation class of BarcodeReader<T>

After implementing these, you use them as follows:

using BitMiracle.LibTiff.Classic;
using ZXing.Net.Bindings.LibTiff;

using var stream = File.Open("MultiPage.tif", FileMode.Open);
using var tiff = Tiff.ClientOpen("in-memory", "r", stream, new TiffStream());

var reader = new BarcodeReader();
int page = 1;
do
{
    Console.WriteLine($"Page {page++}");
    var barcodes = reader.DecodeMultiple(tiff);
    foreach (var barcode in barcodes)
    {
        Console.WriteLine($"Format: {barcode.BarcodeFormat}, Text: {barcode.Text}");
    }

} while (tiff.ReadDirectory());

Now, let's look at the implementation of the classes mentioned above.

Implementation

Implementation class of LuminanceSource

It is no exaggeration to say that this class is practically everything.

using BitMiracle.LibTiff.Classic;

namespace ZXing.Net.Bindings.LibTiff;

/// <summary>
/// Class for extracting luminance information from TIFF images.
/// </summary>
public sealed class TiffLuminanceSource : BaseLuminanceSource
{
    /// <summary>
    /// Initializes a new instance from the specified TIFF image.
    /// </summary>
    /// <param name="tiff">The TIFF image to extract luminance information from.</param>
    /// <exception cref="ArgumentException">Thrown when the TIFF image is not 1-bit.</exception>
    public TiffLuminanceSource(Tiff tiff)
        : base(GetWidth(tiff), GetHeight(tiff))
    {
        var width = Width;
        var height = Height;

        // Check the bit depth of the TIFF image
        var bitsPerSampleField = tiff.GetField(TiffTag.BITSPERSAMPLE);
        if (bitsPerSampleField == null || bitsPerSampleField[0].ToInt() != 1)
            throw new ArgumentException(@"The provided TIFF image is not 1-bit.", nameof(tiff));

        var scanlineSize = tiff.ScanlineSize();
        var scanline = new byte[scanlineSize];

        // Read each scanline and extract luminance information
        for (var row = 0; row < height; row++)
        {
            tiff.ReadScanline(scanline, row);
            unsafe
            {
                fixed (byte* scanlinePtr = scanline)
                {
                    for (var col = 0; col < width; col++)
                    {
                        var byteIndex = col / 8;
                        var bitIndex = 7 - (col % 8); // TIFF stores bits from most significant to least significant
                        var isWhite = (scanlinePtr[byteIndex] & (1 << bitIndex)) != 0;
                        luminances[row * width + col] = isWhite ? (byte)255 : (byte)0;
                    }
                }
            }
        }
    }

    /// <summary>
    /// Initializes a new instance from the specified luminance information, width, and height.
    /// </summary>
    /// <param name="luminances">An array of luminance information.</param>
    /// <param name="width">The width of the image.</param>
    /// <param name="height">The height of the image.</param>
    private TiffLuminanceSource(byte[] luminances, int width, int height)
        : base(luminances, width, height)
    {
    }

    /// <summary>
    /// Creates a new LuminanceSource from new luminance information, width, and height.
    /// </summary>
    /// <param name="newLuminances">A new array of luminance information.</param>
    /// <param name="width">The width of the new image.</param>
    /// <param name="height">The height of the new image.</param>
    /// <returns>A new instance of LuminanceSource.</returns>
    protected override LuminanceSource CreateLuminanceSource(byte[] newLuminances, int width, int height)
    {
        return new TiffLuminanceSource(newLuminances, width, height);
    }

    /// <summary>
    /// Gets the width of the TIFF image.
    /// </summary>
    /// <param name="tiff">The TIFF image to get the width of.</param>
    /// <returns>The width of the TIFF image.</returns>
    /// <exception cref="ArgumentException">Thrown when the TIFF image does not contain the IMAGEWIDTH field.</exception>
    public static int GetWidth(Tiff tiff)
    {
        // Get the IMAGEWIDTH field from the TIFF image
        var widthField = tiff.GetField(TiffTag.IMAGEWIDTH);
        // Throw an exception if the IMAGEWIDTH field does not exist
        return widthField == null
            ? throw new ArgumentException("TIFF image does not contain IMAGEWIDTH field.", nameof(tiff))
            : widthField[0].ToInt();
    }

    /// <summary>
    /// Gets the height of the TIFF image.
    /// </summary>
    /// <param name="tiff">The TIFF image to get the height of.</param>
    /// <returns>The height of the TIFF image.</returns>
    /// <exception cref="ArgumentException">Thrown when the TIFF image does not contain the IMAGELENGTH field.</exception>
    public static int GetHeight(Tiff tiff)
    {
        // Get the IMAGELENGTH field from the TIFF image
        var heightField = tiff.GetField(TiffTag.IMAGELENGTH);
        // Throw an exception if the IMAGELENGTH field does not exist
        return heightField == null
            ? throw new ArgumentException("TIFF image does not contain IMAGELENGTH field.", nameof(tiff))
            : heightField[0].ToInt();
    }

}

Implementation class of BarcodeReader<T>

using BitMiracle.LibTiff.Classic;

namespace ZXing.Net.Bindings.LibTiff;

/// <summary>
/// A barcode reader class for decoding TIFF images.
/// </summary>
public class BarcodeReader() : BarcodeReader<Tiff>(null, DefaultCreateLuminanceSource, null)
{
    /// <summary>
    /// A delegate for creating the default luminance source.
    /// </summary>
    private static readonly Func<Tiff, LuminanceSource> DefaultCreateLuminanceSource =
        (image) => new TiffLuminanceSource(image);
}

Other Useful Extension Methods

While the code provided above is sufficient on its own, creating extension methods like the following makes it even easier to use.

using BitMiracle.LibTiff.Classic;

namespace ZXing.Net.Bindings.LibTiff;

/// <summary>
/// A class providing extension methods for barcode readers.
/// </summary>
public static class BarcodeReaderExtensions
{
    /// <summary>
    /// Decodes a barcode from a TIFF image.
    /// </summary>
    /// <param name="reader">The barcode reader instance.</param>
    /// <param name="image">The TIFF image to decode.</param>
    /// <returns>The result of the decoded barcode.</returns>
    public static Result Decode(this IBarcodeReaderGeneric reader, Tiff image)
    {
        // Create a source to extract luminance information from the TIFF image
        var luminanceSource = new TiffLuminanceSource(image);
        // Decode the barcode using the luminance information
        return reader.Decode(luminanceSource);
    }

    /// <summary>
    /// Decodes multiple barcodes from a TIFF image.
    /// </summary>
    /// <param name="reader">The barcode reader instance.</param>
    /// <param name="image">The TIFF image to decode.</param>
    /// <returns>The results of the decoded multiple barcodes.</returns>
    public static Result[] DecodeMultiple(this IBarcodeReaderGeneric reader, Tiff image)
    {
        // Create a source to extract luminance information from the TIFF image
        var luminanceSource = new TiffLuminanceSource(image);
        // Decode multiple barcodes using the luminance information
        return reader.DecodeMultiple(luminanceSource);
    }
}

That's all!

Discussion