Recursive AI

Decode JPEG 2000 and JBIG2 in OnePDF with C#

OneImage is a free, open-source image library for .NET from Recursive AI. MIT or Apache-2.0, no native dependencies.

RecursiveAI.OneImage.Pdf brings in OnePDF, Recursive AI’s PDF library. OnePDF can’t decode /JPXDecode or /JBIG2Decode images on its own; RegisterDefaults() adds those decoders. Try scans.pdf from the download.

Terminal
dotnet add package RecursiveAI.OneImage.Pdf

Requires .NET 10 (net10.0); .NET 9 and earlier aren’t supported.

C#
using OneImage.Pdf;
using OnePdf;
 
PdfImageCodecs.RegisterDefaults();
using var pdf = PdfDocument.Open("scans.pdf");
pdf.Pages[0].Interpret(new ImageReporter());
 
sealed class ImageReporter : PdfDevice
{
    public override void DrawImage(
        in PdfImage image,
        in PdfGraphicsState state)
    {
        var data = image.GetData();
        if (data is { IsDecoded: true })
        {
            int bytes = data.Samples.Length;
            Console.WriteLine(bytes);
        }
        else
            Console.WriteLine("Not decoded");
    }
}

The example is the full program below: unzip it and dotnet run. To run only the code above, paste it into Program.cs of a new dotnet new console project and dotnet run.

Prints the decoded sample byte count for each of the two images:

Text
384
384

The full program

scans.pdf has one page with two image objects: a 16 × 8 color strip (/JPXDecode) and a 24 × 16 black-and-white pattern (/JBIG2Decode).

C#
using OneImage.Pdf;
using OnePdf;
 
PdfImageCodecs.RegisterDefaults();
using var pdf = PdfDocument.Open("scans.pdf");
pdf.Pages[0].Interpret(new ImageReporter());
 
sealed class ImageReporter : PdfDevice
{
    public override void DrawImage(
        in PdfImage image, in PdfGraphicsState state)
    {
        string? filter = image.Stream?.FilterNames.LastOrDefault();
        var data = image.GetData();
        if (data is { IsDecoded: true })
            Console.WriteLine($"{filter}: {data.Width} × {data.Height} decoded");
        else
            Console.WriteLine($"{filter}: not decoded");
    }
}
Text
JPXDecode: 16 × 8 decoded
JBIG2Decode: 24 × 16 decoded

If an image can’t be decoded, such as when its compressed data is damaged, the program prints not decoded for that draw instead of reading it as pixels.

Variations

Use a private registry instead of the shared one. Populate the new registry, then pass it to GetData in your device callback. Register replaces existing entries in the registry you pass; here the registry starts empty.

C#
var registry = new PdfImageDecoderRegistry();
PdfImageCodecs.Register(registry);
var data = image.GetData(new() { Decoders = registry });

Check that an app decoder stays registered. Insert the statements below before the full program’s ImageReporter class, and put AppDecoder after that class. The wrapper stands in for an app’s own JPEG 2000 decoder.

C#
var registry = PdfImageDecoderRegistry.Default;
var appDecoder = new AppDecoder(PdfImageCodecs.Jpx!);
registry.Register("JPXDecode", appDecoder);
PdfImageCodecs.RegisterDefaults();
registry.TryGet("JPXDecode", out var current);
bool kept = ReferenceEquals(current, appDecoder);
Console.WriteLine($"App decoder kept: {kept}");
 
sealed class AppDecoder(IPdfImageDecoder inner) : IPdfImageDecoder
{
    public PdfDecodedImage? Decode(
        in PdfImageDecodeRequest request,
        CancellationToken cancellationToken) =>
        inner.Decode(in request, cancellationToken);
}

Prints App decoder kept: True.

The short answer

Call PdfImageCodecs.RegisterDefaults() from RecursiveAI.OneImage.Pdf at startup. It fills missing entries in OnePDF’s shared registry for /JPXDecode (JPEG 2000), /JBIG2Decode (JBIG2), and /DCTDecode (JPEG). It leaves a decoder already registered for any of those filters alone.

How do I extract an image from a PDF document?

Use PdfPage.Interpret with a PdfDevice and handle DrawImage. That callback runs when the page draws an image, so a picture drawn twice can produce two callbacks. Call GetData() inside the callback. When IsDecoded is true for an ordinary image, Samples contains the decoded bytes in the final color space, not a standalone JPEG 2000 or JBIG2 file.

If you want to export an image rather than examine it, look at the reported color space and alpha data before wrapping the samples in an image for saving. A stencil (a mask painted with the current color) has alpha rather than ordinary color samples. If you want the whole page including text, drawings and image placement, render the page instead of extracting individual images.

Why is an embedded PDF image not decoding?

First check that the filter you need is registered before interpreting the page. RegisterDefaults() respects PdfImageCodecs.Jpx and PdfImageCodecs.Jbig2 at the time of the call: setting either property to null stops the call from adding that default, but does not remove an existing registration. If your app registers its own decoder, do that before filling defaults so it is clear which one should win. Use Register(registry) instead only when replacing matching registrations is what you intend.

A registered decoder can still reject damaged data or data that exceeds its limits. Check IsDecoded before consuming pixel samples; getting a PdfImageData object back is not by itself evidence that the bytes were decoded.

All oneimage recipes