Skip to content

Convert Markdown Images

Asterios Raptis edited this page Aug 22, 2025 · 2 revisions

πŸ“„ Convert Markdown Images to <figure> Blocks

Overview

The convert_images tool transforms all Markdown image references (![alt](src "title")) into semantic HTML <figure> blocks with captions.
It works both on single files and entire directories (recursive, e.g. manuscript/).

Why?

  • Provides semantic HTML (<figure> + <figcaption>) for better accessibility.

  • Captions are automatically taken from the image title (if present), otherwise from the alt text.

  • Keeps code snippets safe: ignores images inside fenced code blocks (```/~~~) and inline code (`).

  • Reference-style images (![alt][id] + [id]: url "title") are fully supported.

  • Designed for book projects where images need consistent and accessible formatting.


Usage

With Poetry installed and the script registered in pyproject.toml:

Convert a single file

poetry run convert-images manuscript/chapter01.md

Convert an entire folder (recursive)

poetry run convert-images manuscript

Dry-run (only count changes, do not write)

poetry run convert-images manuscript --dry-run

Add a CSS class to <figure>

poetry run convert-images manuscript --figure-class "book-figure"

Enable backups (optional)

By default, no backups are created (we rely on Git for version control).
If you still want .bak files before overwriting:

poetry run convert-images manuscript --backup

Examples

Markdown input

![A cute cat](images/cat.png "Fluffy cat")

Converted HTML

<figure>
  <img src="images/cat.png" alt="A cute cat" />
  <figcaption>
    <em>Fluffy cat</em>
  </figcaption>
</figure>

Testing

Unit tests ensure:

  • Inline & reference-style images are converted.

  • Captions prefer the title, fallback to alt text.

  • Angle-bracket URLs (<file with spaces.png>) are handled.

  • Images in code blocks or inline code are ignored.

  • Directory recursion works across nested folders.

  • Backup handling (--backup) works correctly.

Run all tests with Poetry:

poetry run pytest -q
Clone this wiki locally