Skip to main content

encode_image_for_document

Function encode_image_for_document 

Source
pub fn encode_image_for_document(img: &ExtractedImage) -> Option<EncodedImage>
Expand description

Encode an ExtractedImage into document-ready bytes (a valid PNG or JPEG) suitable for embedding in an OOXML package.

PDF image streams are not directly embeddable: a FlateDecode stream holds raw, decompressed pixel samples (no PNG container), so writing those bytes with a .png name produces a file Word/PowerPoint reject as corrupt. This helper turns each supported image into a real encoded file:

  • JPEG (DCTDecode): the stream already is a JPEG → passed through as image/jpeg (after a \xFF\xD8 signature check).
  • Flate / Raw raw samples: re-encoded as a real PNG using width/height/bits_per_component/color_space. DeviceGray → 8-bit grayscale, DeviceRGB → RGB, DeviceCMYK → RGB (naive conversion). When the colour-space name is opaque (e.g. ICCBased), the component count is inferred from the byte length.
  • Everything else (JPX/JBIG2/CCITT, non-8-bit depths, indexed palettes, or a sample buffer too short for the declared geometry): returns None so the caller embeds nothing rather than corrupt bytes.

This function never returns raw, unencoded bytes labelled as an image.