mermaid-to-image

mermaid-to-image

將 Markdown 檔案中的 Mermaid 程式碼區塊透過 mermaid.ink API 轉換為 PNG 圖片。

0星標
0分支
更新於 2026/7/22
SKILL.md
唯讀
名稱
mermaid-to-image
描述

將 Markdown 檔案中的 Mermaid 程式碼區塊透過 mermaid.ink API 轉換為 PNG 圖片。

技能:Mermaid 轉圖片

將 Markdown(或其他文字)檔案中的 ```mermaid 程式碼區塊轉換為 PNG 圖片,並以圖片參考取代程式碼區塊。適用於不原生支援 Mermaid 的平台(GitHub Pages/Jekyll、Dev.to 等)。


使用時機

  • 使用者要求將檔案中的 Mermaid 圖表轉換為圖片
  • 使用者想要將特定 Mermaid 程式碼區塊渲染為 PNG
  • 發布流程需要靜態圖片而非 Mermaid 程式碼區塊

工作流程

步驟 1:識別目標檔案

使用者可能指定:

  • 單一檔案:convert mermaid blocks in docs/architecture.md
  • 多個檔案:convert mermaid in all files under docs/
  • 特定程式碼區塊:convert the second mermaid block in README.md

掃描目標檔案中的 ```mermaid 程式碼區塊。在繼續前,回報找到多少區塊以及在哪個檔案中。

步驟 2:決定圖片輸出目錄

檢查專案結構,找出圖片通常存放的位置:

# 尋找常見的圖片目錄
ls -d images/ img/ assets/ assets/images/ static/images/ docs/images/ 2>/dev/null

如果存在明確的圖片目錄(例如 images/assets/images/),則使用它。必要時可依主題建立子目錄(例如 images/<topic>/)。

如果沒有明顯的圖片目錄或有多個候選目錄,詢問使用者:

渲染後的 Mermaid 圖片應儲存在哪裡?

1. images/(新建)
2. assets/images/
3. docs/figures/
4. 自訂 — 輸入路徑

步驟 3:將每個圖表渲染為 PNG

使用 mermaid.ink API 渲染圖表。對每個區塊執行以下 Python 程式碼片段:

import base64, urllib.request

def render_mermaid(code: str, output_path: str):
    """透過 mermaid.ink API 將 Mermaid 圖表渲染為 PNG。"""
    encoded = base64.urlsafe_b64encode(code.encode()).decode()
    url = f"https://mermaid.ink/img/{encoded}?bgColor=white"
    req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"})
    resp = urllib.request.urlopen(req, timeout=30)
    with open(output_path, "wb") as f:
        f.write(resp.read())

重要: User-Agent 標頭是必需的——沒有它 mermaid.ink 會回傳 403。

命名慣例

根據圖表內容使用描述性檔名,而非通用名稱:

  • 好:architecture-overview.pngdata-flow.pngheartbeat-sequence.png
  • 不好:mermaid-1.pngdiagram.pngimage1.png

步驟 4:以圖片參考取代程式碼區塊

將每個 ```mermaid ... ``` 區塊取代為 Markdown 圖片參考,使用從檔案到圖片的相對路徑

![Architecture overview](images/topic/architecture-overview.png)

如果專案使用絕對 URL(例如 GitHub Pages),則改用絕對 URL:

![Architecture overview](https://example.github.io/images/topic/architecture-overview.png)

選擇與專案現有圖片參考一致的連結樣式。如果不確定,使用相對路徑。

步驟 5:回報結果

處理完成後,總結:

  • 轉換了多少圖表
  • 圖片儲存在哪裡
  • 哪些檔案被修改

邊緣情況

  • 大型圖表:mermaid.ink 在處理非常複雜的圖表時可能超時。如果渲染失敗,回報錯誤並建議使用者簡化圖表或嘗試其他渲染器。
  • 單一檔案中的多個區塊:依序處理所有區塊,為每個區塊指定獨特的描述性檔名。
  • 已渲染的區塊:如果 mermaid 區塊已有對應的圖片(註解掉或相鄰),則跳過或詢問使用者。
  • 非 Markdown 檔案:相同方法適用於任何包含 mermaid 程式碼區塊的文字檔案(例如 .rst.txt)。