docx/image-format-variety--bmp

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.

Library verdicts: python-docx: — docxjs: —

Metadata

Feature iddocx/image-format-variety--bmp
Formatdocx
Categoryimages
Familydocx/image-format-variety
Axis valuesimg=bmp
Spececma-376-5-part-1 § 17.3.3.9 w:drawing

XPath assertions

ID / partPredicateXPathpython-docxdocxjs
drawing-present-bmp
word/document.xml
exist
A <w:drawing> element must be present in the body.
//w:drawing
default-content-type-bmp
[Content_Types].xml
equal = image/bmp
A <Default> for the image extension with the expected content-type must be registered.
//ct:Default[@Extension='bmp']/@ContentType
media-part-relationship-bmp
word/_rels/document.xml.rels
match = media/image1\.bmp
An image relationship targeting media/image1.<ext> must be declared.
//r:Relationship[@Type='http://schemas.openxmlformats.org/officeDocument/2006/relationships/image']/@Target

Render assertions

No render assertions declared.

Generator source

scripts/gen_image_format_variety.py

#!/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 (expanded)

{
  "$schema": "../manifest.schema.json",
  "id": "docx/image-format-variety--bmp",
  "kind": "literal",
  "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--bmp"
  },
  "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"
  },
  "_expansion": {
    "parent_id": "docx/image-format-variety",
    "bindings": {
      "img": "bmp"
    }
  },
  "assertions": [
    {
      "id": "drawing-present-bmp",
      "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-bmp",
      "part": "[Content_Types].xml",
      "namespaces": {
        "ct": "http://schemas.openxmlformats.org/package/2006/content-types"
      },
      "xpath": "//ct:Default[@Extension='bmp']/@ContentType",
      "must": "equal",
      "value": "image/bmp",
      "description": "A <Default> for the image extension with the expected content-type must be registered."
    },
    {
      "id": "media-part-relationship-bmp",
      "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\\.bmp",
      "description": "An image relationship targeting media/image1.<ext> must be declared."
    }
  ]
}

Fixture

Download image-format-variety--bmp.docx (19.0 KB)

Reference preview

No rendered reference is available for this case.

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.