PDFium Delphi Component Docs

Original image component decoding

Add FPdfImageComponents and create an IPdfImageComponentDecoder with the optional ABI 1 native bridge; no page rendering or RGB bitmap getter is used

CreatePdfImageComponentDecoder loads the selected library, checks ABI exports and validates options; TryCreatePdfImageComponentDecoder returns dependency diagnostics, while cancellation retains its typed exception

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

The decoder's Capabilities advertises picDct8, picJpx8 and picJpx16; Decode returns tightly interleaved unsigned source components and clears samples on failure or cancellation

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

piccDct supports 8-bit samples, sequential/progressive Huffman JPEG and ColorTransform -1, 0 or 1; -1 uses encoded metadata and an Adobe marker takes precedence over the explicit transform

The bridge retains raw CMYK components without automatic inversion; DCT images can apply the PDF Decode array when the document declares inversion

piccJpx supports JP2 containers or raw JPEG 2000 codestreams with 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, including mixed channel precisions; inverse codestream multi-component transforms remain 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 returns unsigned bytes or native-endian words, and raw CMYK channels retain their original channel order; a signed single-component grey source is covered by the focused original-component profile

The caller supplies the color interpretation of these original components; embedded JP2 color labels and ICC metadata do not trigger an additional transform; JPX requires ColorTransform -1 and rejects unsupported channel mappings, inconsistent headers and mismatched geometry

Since v3.357.0 original JPX channels may carry 17- to 24-bit precision; each sample normalizes 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) selects source sample (floor(x/dx),floor(y/dy)) from a validated ceil(Width/dx) by ceil(Height/dy) channel plane; source-cell replication handles nondividing intervals, odd edges and single-sample planes, then signed normalization and the caller's color interpretation apply before ICC conversion

The decoder writes directly into its bounded interleaved output without another full-resolution upsample allocation; this profile does not infer a YCbCr transform from sampling intervals or embedded JP2 color 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 can 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 retains the absolute grid phase, selects 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 colors, JP2 palette/channel projections and unscaled Indexed data; it is an explicit reconstruction policy rather than a guarantee that every viewer uses the same resampling filter or leading-edge behavior

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, while image spans, decoded pixels and byte budgets retain their existing bounds

Native block/precinct alignment can still reject a stream near arithmetic boundaries during full decoding; metadata remains 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 color channels; palettes contain 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 color-only CDEF associations reorder those channels before normalization 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 requested output precision describe the projected color channels, so a 16-bit encoded index plane can legitimately generate 8-bit palette colors; sampled source grids retain 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 remains 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 color 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, including sampled grids; signed values shift into their unsigned source range, while the resulting integer indices retain 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 remain bounded; the index path ignores internal PCLR/CMAP/CDEF interpretations and their payload semantics, using the original single component rather than projected colors; the caller supplies the PDF palette and clamps high indices to its hival

The factory uses optional pdf_image_indices_inspect and pdf_image_indices_decode exports under ABI 1; older DLLs continue to load, 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 color-space selection remain outside this index profile

Optional color declarations

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

Implicit CIELab 14 conversion now decodes 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 retains 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, while scRGB retains 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 for image metadata and an ordered TPdfImageColourSpecifications array of TPdfImageColourSpecification records from the single-codestream JP2 header; each declaration retains Method, signed Precedence, Approximation, EnumeratedColorSpace and owned Data bytes

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

The optional pdf_image_colours_inspect export supplements ABI 1 with a size-checked private record; at most 64 declarations are accepted, aggregate method-data copies observe MaxDecodedBytes, and encoded/sample/pixel limits and cancellation still apply; rejected inspection clears Info and Specifications, while older DLLs return unavailable and keep existing explicit decoding

Document conversion can use supported embedded ICC, sRGB 16, standard-gray 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 when PDF ColorSpace is absent or null; explicit PDF ColorSpace retains priority; optional device fallback covers raw/missing/unsupported declarations, with a separate fallback report count; remaining enumerated families retain 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 containing projected color 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 to avoid losing source precision; metadata inspection observes encoded, decoded-sample and pixel budgets, clears Info on failure or cancellation and does not assert that the entire stream is valid

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

Document color integration

Assign the decoder to TPdfDocumentColourOptions.ImageDecoder before calling ConvertPdfDocumentColours; the default nil value retains the existing unsupported-codec policy

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

DCT DecodeParms supports an empty dictionary or ColorTransform 0/1, including the corresponding entry in a filter parameter array; unresolved or additional decoder parameters reject conversion

An explicit PDF ColorSpace overrides embedded JP2 color declarations; when absent or null, optional IPdfImageColourMetadata enables the supported implicit ICC, sRGB, standard-gray, CMYK and unsigned sYCC paths, with configurable component-count device fallback; source metadata selects actual precision independently of a missing or ignored PDF BitsPerComponent entry, while older bridges retain explicit supported 8/16-bit decoding; ordinary JPX Decode entries are ignored before ICC conversion, including calibrated color spaces and filter chains, as required by ISO 32000-1 section 7.4.9

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

Decoded source components enter the selected ICC transform directly; a complete conversion writes the new OutputIntent, while strict failure leaves the destination unchanged during preparation

TPdfDocumentColourReport.CodecImagesDecoded counts source images actually decoded through the component provider; ImagesConverted continues to count converted image resources

Limits and cancellation

TPdfImageComponentOptions.Default allows 256 MiB each of encoded and decoded bytes, and 16,777,216 pixels; these are also the hard maxima, with each dimension at most 16,384 and at most 4,096 JPX tiles

These logical sample and geometry budgets do not assert an exact process RSS limit for native codec allocations; native calls check cancellation before and after decode without interrupting codec internals

The bridge and its dependency/runtime license notices are optional deployment files; only the recorded ordinary Win64 build has 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;