PDFium Delphi Component Docs

Original image component decoding

Add FPdfImageComponents and obtain an IPdfImageComponentDecoder through the optional ABI 1 native bridge; page rendering and RGB bitmap getters play no part

CreatePdfImageComponentDecoder loads the chosen library, checks the ABI exports and validates the options; TryCreatePdfImageComponentDecoder hands back dependency diagnostics instead, whilst cancellation keeps its typed exception

PdfImageComponentBackendVersions reports the linked codec versions; the qualified bridge builds on libjpeg-turbo 3.2.0 and OpenJPEG 2.5.4, statically linked with generated licence notices

The decoder's Capabilities advertises picDct8, picJpx8 and picJpx16; Decode hands back tightly interleaved unsigned source components and wipes the samples on failure or cancellation

TPdfImageComponentRequest declares Codec, Width, Height, Components, BitsPerComponent and ColorTransform; the component count is 1, 3 or 4, and CMYK is never turned into RGB; for JPX, BitsPerComponent selects unsigned 8/16-bit output and must cover the highest source precision, whilst DCT keeps its exact 8-bit contract

piccDct copes with 8-bit samples, sequential/progressive Huffman JPEG and ColorTransform -1, 0 or 1; -1 defers to the encoded metadata, and an Adobe marker outranks the explicit transform

Raw CMYK components are retained by the bridge without automatic inversion; DCT images can apply the PDF Decode array where the document declares inversion

piccJpx takes JP2 containers or raw JPEG 2000 codestreams carrying signed or unsigned components with validated image/component origins; v3.304.0 introduced independently signed 8/16-bit channels, and v3.306.0 adds source precisions 1 through 16, mixed channel precisions included; inverse codestream multi-component transforms stay part of decoding

A signed channel with source precision p is range-checked and shifted by 2^(p-1), then its unsigned source range 0..2^p-1 scales to the requested 8/16-bit output range with nearest integer rounding; ABI 1 still hands back unsigned bytes or native-endian words, and raw CMYK channels keep their original channel order

The caller supplies the colour interpretation of these original components; embedded JP2 colour labels and ICC metadata trigger no additional transform; JPX insists on ColorTransform -1 and turns away unsupported channel mappings, alpha definitions, inconsistent headers and mismatched geometry

Since v3.357.0 original JPX channels may carry 17- to 24-bit precision; each sample is normalised to the requested 8- or 16-bit output by nearest rounding before colour conversion, and declarations above 24 bits stay unsupported because the bundled OpenJPEG build returns degenerate samples at 31-bit precision

Subsampled component grids since v3.305.0

JPX channels can have independent horizontal and vertical sampling intervals from 1 through 255 with validated image/component origins; the original v3.305.0 profile used common precision 8 or 16, and v3.306.0 also supports mixed source precisions 1 through 16; the requested Width and Height describe the complete reference grid rather than an individual component plane

Each output pixel at (x,y) picks the source sample (floor(x/dx),floor(y/dy)) from a validated ceil(Width/dx) by ceil(Height/dy) channel plane; source-cell replication copes with non-dividing intervals, odd edges and single-sample planes, after which signed normalisation and the caller's colour interpretation apply before ICC conversion

The decoder writes straight into its bounded interleaved output without another full-resolution upsample allocation; this profile infers no YCbCr transform from sampling intervals or embedded JP2 colour labels; precisions above 16 follow the high-precision policy, and embedded opacity is covered by the soft-mask section below

Image, component and tile origins

Since v3.309.0, JPX image and tile origins may be nonzero; Width and Height report the image-area spans Xsiz-XOsiz and Ysiz-YOsiz, and decode output starts at local pixel zero without allocating the unused reference-grid prefix

Component origins are ceil(XOsiz/dx), ceil(YOsiz/dy), and plane sizes subtract those values from the endpoint ceilings; reconstruction keeps the absolute grid phase, picks the source cell containing each reference pixel and extends the first source sample across leading positions before that cell

This source-cell policy applies consistently to direct colours, JP2 palette/channel projections and unscaled Indexed data; it is an explicit reconstruction policy rather than a promise that every viewer uses the same resampling filter or leading-edge behaviour

Tile origins must cover the image start, every source plane must contain samples, and at most 4096 tiles are accepted; absolute endpoints and tile sizes must not exceed 2147483647, whilst image spans, decoded pixels and byte budgets keep their existing bounds

Native block/precinct alignment can still turn away a stream near arithmetic boundaries during full decoding; metadata stays header inspection, and failed or cancelled operations publish no samples

Embedded opacity since v3.353.0

A direct three-colour-component JPX image may carry one CDEF channel of type 1 (raw opacity) registered for the whole image at full resolution; the converter decodes that channel separately, writes an 8-bit DeviceGray /SMask whose samples are the source channel scaled to eight bits, drops SMaskInData and leaves the converted colour samples unchanged

Since v3.381.3 the embedded opacity becomes a soft mask only when the image declares SMaskInData 1; with 0 or no entry, the ISO 32000-2 default, the converter ignores the opacity channel as ISO 32000-1 Table 89 requires, converts the colour channels alone and writes no /SMask, so an existing /SMask or the graphics-state soft mask keeps applying

Opacity inspection and decoding are optional bridge exports (pdf_image_components_opacity and pdf_image_components_decode_opacity) and an optional IPdfImageOpacity decoder interface; providers without them keep the previous behaviour, and a source that declares SMaskInData 1 without a usable soft mask is rejected rather than silently composited as opaque

IPdfImageOpacity.InspectOpacity fills a TPdfImageOpacityInfo without decoding samples: Present reports an opacity channel, Premultiplied marks a CDEF type 2 channel, Source is the zero-based codestream component that carries it and Components is the colour component count the opacity applies to; DecodeOpacity then returns one opacity sample per pixel at the requested width, height and 8- or 16-bit depth, replicated from its own grid when the channel is subsampled

Since v3.354.0 a type 2 premultiplied opacity channel is also accepted: the alpha plane is decoded at the colour depth, each colour sample is divided back by its alpha (zero alpha yields zero colour) before colour conversion, and the mask keeps the unmodified alpha

Since v3.355.0 an explicit PDF ColorSpace keeps the embedded opacity channel: the declared colour space still overrides the JPX colour declaration, while the opacity plane is inspected and decoded separately for the soft mask

Since v3.356.0 the opacity channel may be subsampled: each reference pixel selects the source cell containing it and positions before the first sample extend that first sample, following the same source-cell rule as the colour planes

Since v3.358.0 a channel-mapped (PCLR/CMAP) image may also carry the opacity channel: the CDEF opacity entry names a channel whose CMAP entry maps to a codestream component, and since v3.359.0 that entry may instead select a PCLR column whose values become the mask samples for the source indices

SMaskInData 2, precisions above the supported colour depth and native rendering of the mask remain outside this bounded profile

Component registration since v3.349.0

A CRG marker in the JPEG 2000 main header registers components at sub-grid offsets that a decoded sample grid cannot express, so any nonzero offset now rejects inspection and decoding with an explicit registration diagnostic while the caller's destination stays unchanged

All-zero CRG declarations and sources without CRG keep their previous geometry and produce identical samples; the check walks validated main-header marker segments only, so registration boxes in compositing-layer headers, tile-part CRG fields and resampling policies for registered components remain outside this bounded policy

Registration offsets are not part of the JPX baseline feature set that PDF image XObjects are limited to, so rejecting them explicitly is preferred over publishing unregistered components

JP2 palette and channel mapping

Since v3.307.0, paired PCLR/CMAP boxes project up to four codestream components into 1, 3 or 4 colour channels; palettes hold 1 through 1024 entries and up to 255 columns with signed or unsigned precisions 1 through 16

Mappings can select source components, permute or repeat palette columns, or combine direct and palette channels; complete colour-only CDEF associations reorder those channels before normalisation and ICC conversion

Since v3.361.0 a CDEF list may describe one channel several times: when a channel carries more than one colour association its samples are replicated into each of them, and the projected colour count is the highest association; an association set with a gap below that maximum still rejects

Since v3.362.0 a partial list is accepted: a channel without a description keeps its identity colour association (channel i as colour i+1, skipping an opacity channel or component), so overriding a single association resolves like the undescribed image, while a default that collides with an explicit association or exceeds four still rejects

Metadata and the requested output precision describe the projected colour channels, so a 16-bit encoded index plane may legitimately yield 8-bit palette colours; sampled source grids keep their source-cell replication semantics

Invalid box lengths, unmatched PCLR/CMAP, invalid mappings and unsupported CDEF definitions reject inspection; out-of-range decoded indices and nonzero palette padding reject full decoding without publishing samples; metadata stays header inspection rather than complete stream validation

Since v3.363.0 one CDEF channel may carry both a colour and an opacity description: the channel stays in the colour set and is also decoded as the opacity plane, so a three-component direct or channel-mapped image can declare its third channel as colour 3 plus a type 1 or type 2 opacity channel, with an 8-bit DeviceGray soft mask and premultiplied colour divided back by the shared alpha; a second opacity description rejects

Since v3.365.2 a palette (PCLR/CMAP) image may map that shared channel to a palette column: signed index components are rebiased before the column lookup, so the column supplies both the colour and the opacity sample, including the type 2 premultiplied case

Since v3.364.1 a four-colour image may also share its fourth channel as opacity: the channel stays the fourth colour component and supplies the soft mask, so a 16-bit CMYK source with a 12-bit alpha plane converts with an 8-bit DeviceGray mask

Since v3.364.0 a two-component image may describe its second channel as opacity while the first keeps its identity grey association: the explicit, implicit or device-fallback grey colour channel converts normally and an 8-bit DeviceGray soft mask carries the opacity samples, with premultiplied grey divided back by alpha and 8- or 16-bit, CMAP-mapped or palette-projected sources accepted; a one-component image with an opacity description and two opacity descriptions still reject

Multi-component PDF Indexed input and unsupported implicit colour families remain outside this profile; embedded opacity channels are covered by the soft-mask sections below, and original channel precisions up to 24 bits follow the high-precision policy

Optional JPX index decoding

Since v3.308.0, query IPdfImageIndexDecoder for InspectIndices and DecodeIndices when source samples select a PDF Indexed palette; this separate optional interface preserves the existing component-decoder and metadata contracts

Index decoding accepts one JPX component with validated image/component origins, with signed or unsigned precision 1 through 16, sampled grids included; signed values shift into their unsigned source range, and the resulting integer indices keep their values without intensity scaling

Use the inspected DecodedBitsPerComponent for 8/16-bit storage; the decode request must specify piccJpx, one component, ColorTransform -1 and the complete reference-grid dimensions; a 5-bit index value of 7 remains 7 in either supported storage width, and 16-bit words use native byte order

JP2 box framing, scope and source geometry stay bounded; the index path ignores internal PCLR/CMAP/CDEF interpretations and their payload semantics, using the original single component rather than projected colours; the caller supplies the PDF palette and clamps high indices to its hival

The factory uses the optional pdf_image_indices_inspect and pdf_image_indices_decode exports under ABI 1; older DLLs carry on loading, and index calls return unavailable with empty output instead of falling back to intensity decoding; metadata, pixel, decoded-byte and cancellation guards still apply

Multiple encoded components, source precision above 16, any SMaskInData and implicit PDF colour-space selection stay outside this index profile

Optional colour declarations

Since v3.312.0, an integer Pixel Format box has its complete channel count, unique channel indices and integer format values validated before native decoding; fixed/floating reinterpretations, malformed payloads, duplicate boxes and invalid scope are rejected rather than silently using integer intensities

Implicit CIELab 14 conversion now decodes the original integer ranges, offsets, precision and signedness through optional floating PCS Lab; this does not add encoded fixed/floating JPX support

Since v3.313.0, document conversion also interprets ROMM RGB 21 and 10/12/16-bit extended sRGB 20 through optional floating PCS Lab, retaining original signed/unsigned precision, per-channel sampling and supported palette projections; ROMM uses its unflared encoding equations and extended sRGB keeps negative and greater-than-one linear RGB until PCS conversion

Since v3.314.0, extended sYCC 24 and 16-bit integer scRGB 25/scRGB Gray 26 use the same optional floating PCS transport; extended sYCC applies its own luma/chroma interpretation and inverse matrix, whilst scRGB keeps linear negative and above-white values; this does not infer scRGB-nl or add encoded floating pixel support

Since v3.310.0, query IPdfImageColourMetadata and call InspectColours to obtain image metadata and an ordered TPdfImageColourSpecifications array of TPdfImageColourSpecification records straight from the single-codestream JP2 header; each declaration keeps its Method, signed Precedence, Approximation, EnumeratedColorSpace and owned Data bytes

Data carries the complete METHDAT payload: method 1 opens with the four-byte big-endian enumerated value, methods 2/3 hold ICC profile bytes, and other methods keep their data opaque; metadata inspection preserves input order and does not assert that every declaration can be converted

The optional pdf_image_colours_inspect export adds a size-checked private record on top of ABI 1; at most 64 declarations are accepted, aggregate method-data copies observe MaxDecodedBytes, and the encoded/sample/pixel limits and cancellation still apply; a rejected inspection clears Info and Specifications, whilst older DLLs report unavailable and carry on with existing explicit decoding

Document conversion can use supported embedded ICC, sRGB 16, standard grey 17, CMYK 12, unsigned sYCC 18, integer CIELab 14, ROMM RGB 21, extended sRGB 20, extended sYCC 24 and 16-bit integer scRGB 25/scRGB Gray 26 declarations where the PDF ColorSpace is absent or null; an explicit PDF ColorSpace keeps priority; optional device fallback covers raw, missing and unsupported declarations, with a separate fallback report count; remaining enumerated families keep their accurate-interpretation limits

Optional source metadata since v3.306.0

Query IPdfImageComponentMetadata and call Inspect for bounded JPX header information; TPdfImageComponentInfo reports Width, Height, Components, DecodedBitsPerComponent and a Channels array of TPdfImageComponentChannelInfo records carrying projected colour BitsPerComponent, IsSigned, HorizontalSampling and VerticalSampling

DecodedBitsPerComponent is 8 when every source channel has at most eight bits and 16 otherwise; use it for the decode request so source precision is not lost; metadata inspection observes the encoded, decoded-sample and pixel budgets, clears Info on failure or cancellation, and does not assert that the whole stream is valid

The supplementary native export keeps ABI 1 and checks its metadata buffer size; older bridges without it still load and decode explicit supported 8/16-bit requests, whilst Inspect returns False with an unavailable diagnostic; successful interface discovery alone does not establish that the loaded bridge provides metadata

Document colour integration

Attach the decoder to TPdfDocumentColourOptions.ImageDecoder before calling ConvertPdfDocumentColours; with the default nil value the existing unsupported-codec policy carries on as before

General filters such as ASCIIHex or Flate are decoded first, after which exactly one remaining DCTDecode or JPXDecode filter can be delegated; decoder capability, sample length, dimensions and transform output all stay checked by the document workflow

DCT DecodeParms accepts an empty dictionary or ColorTransform 0/1, including the matching entry within a filter parameter array; decoder parameters that are unresolved or surplus to requirements reject the conversion

An explicit PDF ColorSpace overrides embedded JP2 colour declarations; where it is absent or null, optional IPdfImageColourMetadata opens up the supported implicit ICC, sRGB, standard grey, CMYK and unsigned sYCC paths, with configurable component-count device fallback on top; source metadata selects the actual precision independently of a missing or ignored PDF BitsPerComponent entry, whilst older bridges stick to explicit supported 8/16-bit decoding; ordinary JPX Decode entries are ignored before ICC conversion, calibrated colour spaces and filter chains included, as ISO 32000-1 section 7.4.9 requires

JPX decoder parameter dictionaries and SMaskInData 2 remain unsupported, whilst SMaskInData 1 is accepted only when the source carries an embeddable opacity channel; image masks keep their separate preservation path, and unsupported implicit colour families, alpha inference and multi-component Indexed input stay outside this profile

Decoded source components feed straight into the selected ICC transform; a complete conversion writes out the new OutputIntent, whilst a strict failure leaves the destination untouched during preparation

TPdfDocumentColourReport.CodecImagesDecoded counts the source images genuinely decoded through the component provider; ImagesConverted carries on counting converted image resources

Limits and cancellation

TPdfImageComponentOptions.Default permits 256 MiB apiece of encoded and decoded bytes, plus 16,777,216 pixels; the same figures double as the hard maxima, with each dimension capped at 16,384 and no more than 4,096 JPX tiles

These logical sample and geometry budgets make no claim to an exact process RSS limit on native codec allocations; native calls poll cancellation before and after decode and leave codec internals uninterrupted

The bridge together with its dependency and runtime licence notices is an optional set of deployment files; only the recorded ordinary Win64 build carries current runtime qualification

Public declarations

uses SysUtils, FPdfAsync;

type
  EPdfImageComponentError=class(Exception);
  TPdfImageComponentCodec=(piccDct,piccJpx);
  TPdfImageComponentCapability=(picDct8,picJpx8,picJpx16);
  TPdfImageComponentCapabilities=set of TPdfImageComponentCapability;
  TPdfImageComponentRequest=record
    Codec:TPdfImageComponentCodec;
    Width,Height,Components,BitsPerComponent:Integer;
    ColorTransform:Integer;
  end;
  IPdfImageComponentDecoder=interface
    ['{352A4244-9476-472B-8823-A39FB0605719}']
    function Capabilities:TPdfImageComponentCapabilities;
    function Decode(const Encoded:TBytes; const Request:TPdfImageComponentRequest;
      out Samples:TBytes; out ErrorText:string):Boolean;
  end;
  TPdfImageComponentChannelInfo=record
    BitsPerComponent,HorizontalSampling,VerticalSampling:Integer;
    IsSigned:Boolean;
  end;
  TPdfImageComponentChannelInfos=array of TPdfImageComponentChannelInfo;
  TPdfImageComponentInfo=record
    Width,Height,Components,DecodedBitsPerComponent:Integer;
    Channels:TPdfImageComponentChannelInfos;
  end;
  IPdfImageComponentMetadata=interface
    ['{55022FDD-A21B-4414-86FF-1445EAA2467E}']
    function Inspect(const Encoded:TBytes;Codec:TPdfImageComponentCodec;
      out Info:TPdfImageComponentInfo;out ErrorText:string):Boolean;
  end;
  TPdfImageOpacityInfo=record
    Present,Premultiplied:Boolean;
    Source,Components:Integer;
  end;
  IPdfImageOpacity=interface
    ['{C8B64A52-9F27-4E5D-B0C1-6A2F0D3E8B41}']
    function InspectOpacity(const Encoded:TBytes;out Info:TPdfImageOpacityInfo;
      out ErrorText:string):Boolean;
    function DecodeOpacity(const Encoded:TBytes;Width,Height,Components,
      BitsPerComponent:Integer;out Samples:TBytes;out ErrorText:string):Boolean;
  end;
  TPdfImageComponentOptions=record
    MaxEncodedBytes,MaxDecodedBytes,MaxPixels:Integer;
    CancellationToken:IPdfCancellationToken;
    class function Default:TPdfImageComponentOptions; static;
  end;

function CreatePdfImageComponentDecoder(const LibraryPath:string;
  const Options:TPdfImageComponentOptions):IPdfImageComponentDecoder;
function TryCreatePdfImageComponentDecoder(const LibraryPath:string;
  const Options:TPdfImageComponentOptions; out Decoder:IPdfImageComponentDecoder;
  out ErrorText:string):Boolean;
function PdfImageComponentBackendVersions(const LibraryPath:string):string;