AddImageFromString

Image handling

Description

Adds an image from memory to the selected document

Once an image has been added to the document it can be drawn on any page multiple times without further increasing the size of the PDF file

Supported image file types are BMP, TIFF, JPEG, PNG, GIF, WMF, EMF and WebP, plus AVIF, HEIF, HEIC and JPEG XL when a modern image decoder is available

PDF version behaviour: importing 16-bit-per-component image data requires PDF 1.5. When a document is set to PDF 1.4 or lower and the save version is not locked, AddImageFromString automatically raises the document to PDF 1.5 and records 16-bit image samples in AutoBumpedFeatures. If the caller locks a lower save version, the compatibility gate rejects the save with LastErrorCode 602

For BMP and TIFF images, the CompressImages function can called before calling this function to compress the image data. Other image types are automatically compressed

The built-in TIFF path accepts bounded BigTIFF strips, classic TIFF or BigTIFF tiles and separate-plane, palette-colour or 16-bit classic TIFF strips with page selection through nonnegative Options; page numbers start at 1 and 0 selects the first page; a Compression value that the built-in path does not implement, such as PixarLog (32909), SGILog (34676, 34677) or ZSTD (50000), fails with an error that names the value instead of producing an empty image

BigTIFF and classic tiled TIFF import support unsigned chunky 1-, 2-, 4- and 8-bit greyscale or palette samples and 8-bit RGB or CMYK samples with compatible uncompressed, LZW, Deflate, CCITT, JPEG or PackBits pixel blocks; JPEG pixel blocks follow the coding-process rules described below; CCITT requires bilevel greyscale; Modified Huffman data (compression 2, or 32771 with word-aligned rows) and Group 3 or Group 4 data whose T4Options or T6Options allow uncompressed mode are decoded to uncompressed bilevel samples; JPEG-compressed CMYK samples (PhotometricInterpretation 5) are embedded as ink amounts without inversion whether or not the JPEG data carries an Adobe APP14 marker (decoded 12-bit or arithmetic-coded blocks whose APP14 marker declares YCCK, transform 2, are first converted to CMYK, as readers do for 8-bit DCTDecode data), whereas standalone four-component JPEG files keep the inverted Adobe convention; old-style JPEG (compression 6) images whose JPEGInterchangeFormat field locates a complete JPEG stream import that stream as the image; baseline old-style strips with JPEGQTables, JPEGDCTables and JPEGACTables offsets or a tables-only interchange stream import with those tables, each strip coded on its own and the JPEGRestartInterval and YCbCrSubSampling fields honoured, for greyscale and RGB samples as well as YCbCr, whilst old-style JPEG with a JPEGProc other than baseline (1), such as lossless (14), and tiled old-style JPEG produce explicit errors, as do table-based old-style strips stored in separate planes; resolution fields stored with an invalid data type are ignored

8-bit YCbCr samples outside JPEG, uncompressed or with LZW, Deflate or PackBits and 1, 2 or 4 times chroma subsampling, are converted to RGB with the YCbCrCoefficients and ReferenceBlackWhite fields; without subsampling they may also use horizontal prediction, separate planes and one unassociated or unspecified extra channel, whilst subsampled YCbCr with prediction, separate planes or extra channels, and YCbCr with associated alpha, produce explicit errors; CIELab and ICCLab samples (8-bit or 16-bit) import as a Lab colour space whose white point follows the WhitePoint field or defaults to D65; an embedded Lab-space ICC profile is validated but not needed to interpret them; without an embedded ICC profile, TIFF WhitePoint and PrimaryChromaticities fields select a CalGray or CalRGB colour space (missing values default to D65 and ITU-R BT.709 primaries, and the gamma follows the TransferFunction or defaults to 2.2); up to sixteen extra channels after unsigned 8-bit or 16-bit greyscale, RGB or CMYK samples, or after unsubsampled 8-bit YCbCr samples, are supported: when the first one is unassociated alpha it becomes a soft mask, associated alpha becomes a soft mask with a black Matte, and unspecified extra channels are dropped; signed 8-bit, 16-bit and 32-bit samples are offset by half their range, 32-bit integer samples (also with horizontal prediction under LZW or Deflate) keep their most significant 16 bits, and 16-bit, 32-bit and 64-bit floating-point samples, including the floating-point predictor with LZW or Deflate, are mapped from the SMinSampleValue to SMaxSampleValue range (0 to 1 when absent) to clamped 16-bit samples; an alpha channel that is not the first extra channel, extra channels with palette or JPEG data, signed or floating-point palette, CCITT or JPEG images and other unqualified high-depth layouts produce explicit errors; writing BigTIFF is not provided

Separate unsigned 8-bit or 16-bit RGB and CMYK planes are supported in classic TIFF and BigTIFF strips or tiles with uncompressed, LZW, Deflate or PackBits storage and both fill orders, and 8-bit or 16-bit planes may also hold Huffman lossless JPEG (SOF3), each plane coded as its own single-component frame; horizontal prediction is restored independently for each compatible compressed plane before lossless interleaving

Unsigned 8-bit chunky PackBits greyscale, RGB and CMYK support both fill orders; reversed-fill packed 1-, 2- and 4-bit greyscale preserves each independently padded row, and compatible palette conversion retains its documented precision

PackBits CMYK and reversed-fill blocks are decoded to bounded uncompressed sample blocks before PDF insertion; truncated literal or repeated packets and incorrect expanded lengths reject without changing the image collection

Embedded TIFF ICCProfile tag 34675 supports bounded UNDEFINED profile bytes with accepted v2.0–v2.4 or v4.0–v4.2 headers, supported input/display/output/colour-space classes and matching GRAY, RGB or CMYK data spaces; header size, signature, connection space, rendering intent and all tag-data ranges are checked before insertion

The complete profile is embedded once per imported image and shared by its image blocks through explicit ICCBased colour spaces; palette output uses an ICCBased RGB base, and JPEG, separate-plane, 16-bit, padded-tile and oriented images retain their sample precision

These images use image XObjects instead of inline images so each ICC stream reference resolves explicitly; profile-bearing single-strip Group 4 writer round trips retain the original profile bytes

The importer requests PDF 1.5 for accepted v2 profiles and PDF 1.7 for accepted v4 profiles when the save version is unlocked; a lower locked version that supports ICCBased retains an explicit DeviceGray, DeviceRGB or DeviceCMYK Alternate space for readers that cannot process the profile, whilst targets below PDF 1.3 reject at save

Profile checks establish bounded structure and source-colour compatibility, not complete certification of every internal ICC transform tag; unsupported profile classes, colour spaces or versions reject explicitly, and other TIFF transfer-function or chromaticity metadata remains outside this import qualification

TIFF Orientation values 1 through 8 are applied to the complete clipped image through a PDF Form transform, preserving the original sample precision and codec payloads; quarter turns exchange the reported width, height and horizontal/vertical resolution

TIFF container resolution takes precedence over embedded JPEG density when present; an absent Orientation defaults to 1, and invalid values or fields other than a single SHORT reject before image insertion

Unsigned 16-bit greyscale, RGB and CMYK samples are imported without precision loss from chunky or separate classic TIFF and BigTIFF strips or tiles with uncompressed, LZW, Deflate or PackBits storage and both fill orders

Horizontal prediction is restored per component modulo 65536 in the source byte order; PDF image streams retain all sample bits in big-endian order and require at least PDF 1.5, including images composed from multiple strips or tiles

Native bitmap rendering uses the high byte of each 16-bit sample for its 8-bit display surface; the embedded PDF retains the full precision, and WhiteIsZero greyscale retains its inverse decode mapping

Palette-colour TIFF with 1-, 2-, 4-, 8- or 16-bit unsigned indices supports bounded uncompressed, LZW, Deflate or PackBits blocks in classic TIFF and BigTIFF strips or tiles, both byte orders and both fill orders; compatible horizontal prediction applies to 8-bit or 16-bit indices before colour lookup

Indices wider than 8 bits or palette colours that cannot be represented exactly by 8-bit components expand to 16-bit RGB without discarding palette precision; all 65536 entries of a 16-bit index table remain addressable

Exactly byte-representable palettes with at most 256 entries retain compact PDF Indexed output and their original sample depth; reversed-fill PackBits palettes use the normalised RGB path

Palette expansion checks the full RGB output size, including padded tiles, before decoding; both decoded index bytes and expanded RGB bytes count against the cumulative decoded-work budget, and malformed palette types, counts or ranges reject before image insertion

Classic strips with unsupported sample depths, unqualified depth field types or out-of-range depth field counts enter bounded validation instead of falling back to a lossy bitmap interpretation

Single-component PlanarConfiguration=2 layouts retain compatible packed greyscale or exactly byte-representable palette samples and codecs; high-precision palette colours and 16-bit samples use the normalised raw-block path; separate JPEG colour planes and other unqualified layouts produce explicit errors

Separate colour-plane conversion, palette expansion and 16-bit sample normalisation append raw blocks to the bounded import view without resampling, whilst retaining original source bytes, page identities and full padded tile geometry; plane counts, final partial strips, decoded work and expanded-view size are checked before public image insertion

BigTIFF import also accepts word-aligned directories and external field data for interoperability with existing writers; eight-byte header offsets, range checks, directory cycles and resource limits remain enforced, and odd metadata offsets reject

TIFF input and normalised import views are each limited to 256 MiB; BigTIFF and classic tiled TIFF also bound directory work, retained metadata values, decoded image size and retained pixel-block payload, reject cyclic or out-of-range directories encountered during page selection, and verify block counts and uncompressed, PackBits, LZW or Deflate decoded sizes

Tiles retain their complete encoded width and height, including padded edge pixels, and are clipped to the image bounds; a single padded tile follows the same rule as a tile grid

Tile dimensions must be positive multiples of 16 within the supported range, padded decoded tiles together must fit the 256 MiB budget, and mixed strip and tile layouts are rejected; JPEG frame dimensions must match the full tile or the actual strip dimensions

BigTIFF and classic tiled TIFF LZW payloads require valid codes, an initial nine-bit ClearCode, an explicit end-of-information marker in the final encoded byte and the exact expected decoded byte count; Deflate payloads require a complete checksum-valid zlib stream, no trailing input and the exact decoded size

BigTIFF and classic tiled TIFF LZW import ignores the zero to seven unused bits in the final EOI byte regardless of their values; additional complete bytes, concatenated streams, missing initial ClearCode and truncated termination reject before image insertion

Separate-plane conversion, palette expansion, 16-bit sample normalisation and CCITT Group 3/4, JPEG, LZW and Deflate validation together have a cumulative 256 MiB decoded-work budget across the pages being loaded; selecting one page validates its payload without decoding skipped pages

BigTIFF and classic tiled TIFF Group 4 payloads require complete declared rows, valid changing elements and run lengths, an EOFB marker immediately after the image rows, and only zero bits for terminal byte alignment; extra bytes, reserved options and unqualified uncompressed extension mode are rejected

BigTIFF and classic tiled TIFF Group 3 payloads require a complete EOL before each declared row, a one-dimensional first row in mixed mode, legal bounded runs and transitions, and zero terminal padding; RTC may be omitted or contain exactly six consecutive EOL codes with consistent mixed-mode tag bits

Group 3 supports T4Options 0, 1, 4 and 5, both fill orders, EOL alignment or mixed EOL/tag alignment, and optional byte padding before RTC; truncated rows or controls, trailing bytes, reserved options and uncompressed extension mode reject before image insertion

Framed Group 3 rendering preserves pixels for aligned one-dimensional and mixed two-dimensional data, including single-strip TIFF output

8-bit Huffman DCT JPEG blocks (baseline SOF0, extended sequential SOF1 or progressive SOF2 with 8-bit precision and 8-bit samples) are embedded unchanged as DCTDecode data after a full entropy check: every scan, all required image blocks, referenced coding tables, restart intervals and marker order, one-bit entropy padding, consistent progressive refinement and a terminal EOI without trailing bytes are verified, but no pixels are reconstructed

Coding processes that PDF DCTDecode cannot carry portably are decoded by the library and embedded as image samples, with the frame marker of the first block selecting the process for the whole image: Huffman lossless JPEG (SOF3) with all seven predictors and point transforms, whose precision must equal BitsPerSample (8 or 16), whose components must all be sampled 1x1 and whose restart intervals must cover whole rows; 12-bit Huffman JPEG (sequential SOF1 or progressive SOF2) with 12-bit samples; and arithmetic-coded JPEG (sequential SOF9 or progressive SOF10) whose 8-bit or 12-bit precision matches BitsPerSample, including DAC conditioning tables, restart intervals and progressive refinement scans

Decoded DCT data accepts any sampling factors: subsampled components are replicated to full resolution by pixel repetition without interpolation, and YCbCr from arithmetic-coded or 12-bit JPEG is converted to RGB with the JFIF equations, so the YCbCrCoefficients, YCbCrSubSampling and ReferenceBlackWhite fields do not change JPEG colours; 12-bit samples are widened to 16 bits by bit replication (4095 becomes 65535) and, like 16-bit lossless samples, are embedded as 16-bit image data, which needs PDF 1.5 as described above; decoded samples of every kind (JPEG, floating-point, CIELab, separate planes and other normalised layouts) are stored unfiltered by default and Flate-compressed when CompressImages is enabled, like uncompressed TIFF and BMP data; this applies to chunky 12-bit greyscale, RGB, CMYK and YCbCr samples, with CMYK kept as ink amounts as described above

Shared JPEGTables must be a complete tables-only JPEG datastream; image blocks may reference these tables but cannot redefine them or depend on tables from another block

TIFF shared-table processing keeps the quantization, Huffman and arithmetic-conditioning (DAC) definitions of JPEGTables, so arithmetic-coded blocks decode with conditioning stored once for the page; a global restart interval and application or comment segments in JPEGTables are ignored and never override the state of an image block

JPEG coefficient state for progressive and decoded blocks is limited to 256 MiB and entropy processing to 1,073,741,824 coefficient visits per block

The following JPEG data produces explicit errors instead of being embedded as data that readers cannot display: hierarchical JPEG (SOF5 to SOF7, SOF13 to SOF15 and DHP), arithmetic-coded lossless JPEG (SOF11), DNL and other unqualified markers; lossless JPEG whose precision is not 8 or 16 bits (12-bit lossless included) or differs from BitsPerSample, lossless JPEG with subsampled components and lossless YCbCr; and 8-bit Huffman, 12-bit or arithmetic-coded JPEG stored in separate colour planes

A standalone JPEG file is embedded unchanged as DCTDecode data, so it must use a baseline, extended sequential or progressive DCT frame (SOF0 to SOF2) with 8-bit samples and one, three or four components; a lossless frame (SOF3), 12-bit samples or any other component count makes the function return 0 instead of storing an image that readers cannot display

Single-strip TIFF images retain CCITT decode parameters and LZW or Deflate predictor settings in the generated PDF

For 16-bit greyscale or RGB PNG images with a transparency colour key, reducing the image to 8 bits whilst importing transparency (for example, Options = 5) compares the original 16-bit samples before reduction and preserves the resulting transparency as a soft mask

GIF import retains the logical-screen background outside an opaque frame rectangle; uncovered pixels alone do not imply transparency without a graphic-control transparency declaration

Syntax

Delphi

Function TPDFlib.AddImageFromString(Const Source: AnsiString; Options: Integer): Integer;

DLL

int DLAddImageFromString(int InstanceID, const char* Source, int Options);

Parameters

SourceA string containing the image data. In the ActiveX version of the library this string must contain 16-bit characters, only the lower 8-bits of each character will be used
OptionsFor multi-page TIFF images this parameter specifies the page number to load. For PNG images: 0 = Load the image as usual 1 = Load the alpha channel as a greyscale image 2 = Load the image and alpha channel (limit alpha to 8-bit) 3 = Load the image (limit image 8-bit/channel) 4 = Load the alpha channel (limit to 8-bit/channel) 5 = Load the image with alpha channel (limit both to 8-bit/channel) 6 = Load the image and alpha channel 7 = Load the image and ICC colour profile 8 = Load the image, alpha channel and ICC colour profile while retaining high bit depth. With 7 or 8, a PNG without an embedded profile is still colour managed from its colour chunks: an sRGB chunk selects the sRGB profile, and a gAMA chunk, with the primaries and white point of a cHRM chunk or the sRGB ones, gives a CalRGB space (CalGray for grey images) For other image types this parameter should be set to 0. Setting Options to -1 forces TIFF, EMF and WMF images to be loaded using the GDI+ graphics library. Multipage TIFF images can also be loaded using GDI+ by setting the Options parameter to -PageNumber (for example -3 for page 3)

Return values

0The image data was invalid or the image was in an unsupported format
1The image was added successfully. The value returned is the ImageID which can be used with functions like SelectImage and DrawImage

PNG input validation

PNG input must contain complete chunks and a complete, zero-length IEND chunk; truncated input and unsupported header values return failure