docx/image-format-variety

An inline 1x1 image in each of five raster formats — PNG, JPEG, GIF, BMP, TIFF — confirming content-type + media-part extension are wired per format.

Cases (5)

Feature IDAxis bindingspython-docxdocxjs
docx/image-format-variety--bmpimg=bmp
docx/image-format-variety--gifimg=gif
docx/image-format-variety--jpegimg=jpeg
docx/image-format-variety--pngimg=png
docx/image-format-variety--tiffimg=tiff

Aggregate

LibraryPassFailPending
python-docx005
docxjs005

Parameter axes

Spec notes

python-docx accepts a wide range of raster image formats on Run.add_picture. For each format the package receives (1) a word/media/imageN.<ext> part, (2) a Default content-type mapping for the extension in [Content_Types].xml, and (3) an image relationship from word/_rels/document.xml.rels. This family pins all three wiring steps per format. The sibling docx/image-inline manifest only covers PNG; this family extends coverage to JPEG, GIF, BMP, TIFF — the five raster formats python-docx recognises via its image-header inspector.

Generator source

scripts/gen_image_format_variety.py — runs with --arg_template --format {img.id} --ext {img.ext} --content-type {img.content_type} --out fixtures/docx/image-format-variety--{img.id}.docx

#!/usr/bin/env python3
"""Generate a ``fixtures/docx/image-format-variety--<format>.docx`` fixture.

Parameterised generator for the ``docx/image-format-variety`` family. Each
invocation builds a 1x1 raster image in the requested format (PNG, JPEG,
GIF, BMP, TIFF) and inserts it inline via ``run.add_picture``. Pins the
three wiring steps that must land when a non-PNG image is embedded:
the <Default> content-type registration, the media-part filename, and the
image relationship. Images are synthesised with PIL so nothing binary is
vendored into the corpus.
"""

from __future__ import annotations

import argparse
import io
import tempfile
from pathlib import Path

from PIL import Image

from docx import Document
from docx.shared import Inches

_REPO_ROOT = Path(__file__).resolve().parent.parent


def _synthesise(fmt: str) -> bytes:
    """Return raw bytes of a 1x1 image in `fmt` (PIL format identifier).

    JPEG/BMP/TIFF want an RGB image; GIF/PNG are happy with either. A fixed
    colour + minimum dimension keeps byte-count low and output deterministic.
    """
    img = Image.new("RGB", (1, 1), color=(255, 255, 255))
    buf = io.BytesIO()
    save_kwargs: dict = {}
    if fmt == "JPEG":
        save_kwargs = {"quality": 50}
    img.save(buf, format=fmt, **save_kwargs)
    return buf.getvalue()


_FORMAT_ALIAS = {
    "png":  "PNG",
    "jpeg": "JPEG",
    "gif":  "GIF",
    "bmp":  "BMP",
    "tiff": "TIFF",
}


def _write(fmt_id: str, ext: str, content_type: str, out: Path) -> None:
    pil_fmt = _FORMAT_ALIAS[fmt_id]
    img_bytes = _synthesise(pil_fmt)

    # python-docx's image header parser reads from disk, so stage the bytes
    # in a fixed-name tempfile — random basenames leak into the package XML
    # via pic:cNvPr/@name and defeat reproducible saves.
    tmp_path = Path(tempfile.gettempdir()) / f"corpus-image-format-variety.{ext}"
    tmp_path.write_bytes(img_bytes)

    doc = Document()
    doc.add_paragraph().add_run().add_picture(str(tmp_path), width=Inches(0.5))
    out.parent.mkdir(parents=True, exist_ok=True)
    doc.save(out, reproducible=True)
    tmp_path.unlink(missing_ok=True)


def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument("--format", required=True, help="id: png/jpeg/gif/bmp/tiff")
    parser.add_argument("--ext", required=True)
    parser.add_argument("--content-type", required=True)
    parser.add_argument("--out", required=True)
    ns = parser.parse_args()

    out = Path(ns.out)
    if not out.is_absolute():
        out = _REPO_ROOT / out
    _write(ns.format, ns.ext, ns.content_type, out)
    print(out)
    return 0


if __name__ == "__main__":
    raise SystemExit(main())

Manifest (parent, unexpanded)

{
  "$schema": "../manifest.schema.json",
  "id": "docx/image-format-variety",
  "kind": "parameterised",
  "title": "Image format variety (parameterised)",
  "format": "docx",
  "category": "images",
  "roles": [
    "authoring"
  ],
  "summary": "An inline 1x1 image in each of five raster formats — PNG, JPEG, GIF, BMP, TIFF — confirming content-type + media-part extension are wired per format.",
  "spec": {
    "source": "ecma-376-5-part-1",
    "clause": "17.3.3.9",
    "element": "w:drawing",
    "rnc_reference": "spec/ecma-376-5/part-1/rnc/WordprocessingML.rnc",
    "xsd_reference": "spec/ecma-376-5/part-1/xsd/wml.xsd",
    "notes": "python-docx accepts a wide range of raster image formats on Run.add_picture. For each format the package receives (1) a word/media/imageN.<ext> part, (2) a Default content-type mapping for the extension in [Content_Types].xml, and (3) an image relationship from word/_rels/document.xml.rels. This family pins all three wiring steps per format. The sibling docx/image-inline manifest only covers PNG; this family extends coverage to JPEG, GIF, BMP, TIFF — the five raster formats python-docx recognises via its image-header inspector."
  },
  "fixtures": {
    "machine": "docx/image-format-variety"
  },
  "generator": {
    "python": "scripts/gen_image_format_variety.py",
    "arg_template": "--format {img.id} --ext {img.ext} --content-type {img.content_type} --out fixtures/docx/image-format-variety--{img.id}.docx"
  },
  "parameters": {
    "img": [
      {
        "id": "png",
        "ext": "png",
        "content_type": "image/png"
      },
      {
        "id": "jpeg",
        "ext": "jpeg",
        "content_type": "image/jpeg"
      },
      {
        "id": "gif",
        "ext": "gif",
        "content_type": "image/gif"
      },
      {
        "id": "bmp",
        "ext": "bmp",
        "content_type": "image/bmp"
      },
      {
        "id": "tiff",
        "ext": "tiff",
        "content_type": "image/tiff"
      }
    ]
  },
  "assertions_template": [
    {
      "id": "drawing-present-{img.id}",
      "part": "word/document.xml",
      "namespaces": {
        "w": "http://schemas.openxmlformats.org/wordprocessingml/2006/main"
      },
      "xpath": "//w:drawing",
      "must": "exist",
      "description": "A <w:drawing> element must be present in the body."
    },
    {
      "id": "default-content-type-{img.id}",
      "part": "[Content_Types].xml",
      "namespaces": {
        "ct": "http://schemas.openxmlformats.org/package/2006/content-types"
      },
      "xpath": "//ct:Default[@Extension='{img.ext}']/@ContentType",
      "must": "equal",
      "value": "{img.content_type}",
      "description": "A <Default> for the image extension with the expected content-type must be registered."
    },
    {
      "id": "media-part-relationship-{img.id}",
      "part": "word/_rels/document.xml.rels",
      "namespaces": {
        "r": "http://schemas.openxmlformats.org/package/2006/relationships"
      },
      "xpath": "//r:Relationship[@Type='http://schemas.openxmlformats.org/officeDocument/2006/relationships/image']/@Target",
      "must": "match",
      "value": "media/image1\\.{img.ext}",
      "description": "An image relationship targeting media/image1.<ext> must be declared."
    }
  ]
}