
Diagram To Image
- 466 installs
- 130 repo stars
- Updated June 19, 2026
- sugarforever/01coder-agent-skills
diagram-to-image is a Claude Code skill with a Node CLI that renders Mermaid diagrams or markdown tables to PNG from the terminal for developers creating README, spec, and launch documentation assets.
About
diagram-to-image is a Claude Code skill bundling a Node.js CLI that converts Mermaid diagrams and markdown tables into PNG images from the terminal. The CLI accepts an input file and required -o output flag, auto-detecting content type or forcing mermaid or table mode explicitly. It supports 10 visual themes including default, dark, forest, and blueprint, plus scale factors from 1 to 4 with a default of 2, configurable background color, and a remote render server defaulting to diagramless.xyz. Developers reach for it when README files, architecture specs, or launch materials need checked-in PNG diagrams without opening a design tool.
- Node CLI: diagram-to-image with required -o PNG output
- Auto-detects mermaid vs table via --type auto|mermaid|table
- 10 named themes (default, dark, forest, neutral, ocean, emerald, midnight, slate, lavender, blueprint)
- Scale factor 1–4 (default 2) and optional --bg background color
- Remote render default server https://diagramless.xyz with --server override
Diagram To Image by the numbers
- 466 all-time installs (skills.sh)
- +17 installs in the week ending Jul 27, 2026 (Skillselion tracking)
- Ranked #124 of 550 CLI & Terminal skills by installs in the Skillselion catalog
- Security screen: LOW risk (skills.sh audit)
- Data as of Aug 4, 2026 (Skillselion catalog sync)
npx skills add https://github.com/sugarforever/01coder-agent-skills --skill diagram-to-imageAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 466 |
|---|---|
| repo stars | ★ 130 |
| Security audit | 3 / 3 scanners passed |
| Last updated | June 19, 2026 |
| Repository | sugarforever/01coder-agent-skills ↗ |
How do you render Mermaid diagrams to PNG from the terminal?
Render Mermaid diagrams or markdown tables to PNG from the terminal for READMEs, specs, and launch assets.
Who is it for?
Developers who maintain README and spec diagrams and want repeatable terminal PNG exports without manual screenshotting.
Skip if: Interactive diagram editing or vector SVG output when PNG raster images are not the desired format.
When should I use this skill?
A developer needs to convert a Mermaid file or markdown table to PNG for a README, spec, or launch asset from the CLI.
What you get
PNG image file rendered from Mermaid source or markdown table with chosen theme and scale.
- PNG diagram image
By the numbers
- Supports 10 visual themes for PNG output
- Accepts scale factors 1-4 with default scale 2
- Handles 3 content types: auto, mermaid, and table
Files
Diagram to Image
Convert Mermaid diagrams and Markdown tables to PNG images via the mermaid-red API (diagramless.xyz). Produces high-quality, styled output with custom themes — no heavy local dependencies needed.
When to Use
Use this skill when:
- User has a Mermaid diagram that needs to be converted to an image
- User has a Markdown table that needs to be converted to an image
- User is writing content for X/Twitter and needs visual exports
- User asks to "convert to image", "export as PNG", "make this an image", or similar
Prerequisites
The bundled script uses Node.js built-in fetch (Node 18+). No npm install needed.
# The render script is bundled with this skill:
SKILL_DIR=~/.claude/skills/diagram-to-image/scripts
ls $SKILL_DIR/diagram-to-image.mjsSmart Output Location
IMPORTANT: Determine the best output location based on context. Follow this decision tree:
1. User Specifies Path
If user explicitly mentions a path or filename, use that.
2. Project Context Detection
Check for common image/asset directories in the current project:
# Check for existing image directories (in order of preference)
ls -d ./images ./assets ./img ./static ./public/images ./assets/images 2>/dev/null | head -1Use the first existing directory found. Common patterns:
./images/- General projects./assets/- Web projects./assets/images/- Structured web projects./public/images/- Next.js, React projects./static/- Hugo, other static site generators./img/- Short form convention
3. Article/Document Context
If user is writing an article or document:
- Look for the document's directory
- Create
images/subdirectory if appropriate - Name the image based on the document name + descriptor
4. Conversation Context
Analyze the conversation to determine:
- What the diagram represents → Use for filename (e.g.,
auth-flow.png,user-journey.png) - Related file being discussed → Place image near that file
- Topic being discussed → Use for naming
5. Default Fallback
If no context clues:
- Use current working directory
- Generate descriptive filename from diagram content
Filename Generation
Create meaningful filenames based on content analysis:
| Content Pattern | Example Filename |
|---|---|
flowchart with auth/login | auth-flow.png |
sequenceDiagram with API | api-sequence.png |
erDiagram | entity-relationship.png |
pie chart about X | x-distribution.png |
gantt chart | project-timeline.png |
| Table with comparison | comparison-table.png |
| Table with data | data-table.png |
Rules:
- Use kebab-case (lowercase with hyphens)
- Keep names concise but descriptive (2-4 words)
- Avoid generic names like
diagram.pngorimage.png - Include topic/subject when identifiable
Conversion Process
Step 1: Analyze Context
Before converting, gather context: 1. Check current working directory 2. Look for existing image directories 3. Analyze diagram/table content for naming 4. Consider any files or topics mentioned in conversation
Step 2: Determine Output Path
# Example logic (implement mentally, not as literal script)
if user_specified_path:
output_path = user_specified_path
elif exists("./images"):
output_path = "./images/{generated_name}.png"
elif exists("./assets"):
output_path = "./assets/{generated_name}.png"
elif exists("./public/images"):
output_path = "./public/images/{generated_name}.png"
else:
output_path = "./{generated_name}.png"Step 3: Create Temporary Input File
# For Mermaid diagrams
cat > /tmp/diagram.mmd << 'DIAGRAM_EOF'
<mermaid content>
DIAGRAM_EOF
# For Markdown tables
cat > /tmp/table.md << 'TABLE_EOF'
<table content>
TABLE_EOFStep 4: Convert via mermaid-red API
The API auto-detects content type (mermaid vs table). Both use the same command.
Using the bundled script:
# Mermaid diagram
node ~/.claude/skills/diagram-to-image/scripts/diagram-to-image.mjs /tmp/diagram.mmd -o <output_path>.png
# Markdown table
node ~/.claude/skills/diagram-to-image/scripts/diagram-to-image.mjs /tmp/table.md -o <output_path>.png
# With custom theme
node ~/.claude/skills/diagram-to-image/scripts/diagram-to-image.mjs /tmp/diagram.mmd -o <output_path>.png --theme ocean
# Force content type (if auto-detect gets it wrong)
node ~/.claude/skills/diagram-to-image/scripts/diagram-to-image.mjs /tmp/table.md -o <output_path>.png --type tableAvailable options:
--theme <name>— default, dark, forest, neutral, ocean, emerald, midnight, slate, lavender, blueprint--type <type>— auto (default), mermaid, table--scale <n>— 1-4 (default: 2, for 2x DPI)--bg <color>— Background color (default: white, use "transparent" for no bg)--server <url>— Override server (default: https://diagramless.xyz)
Piping from stdin also works:
echo "graph TD; A-->B" | node ~/.claude/skills/diagram-to-image/scripts/diagram-to-image.mjs -o out.png
cat /tmp/table.md | node ~/.claude/skills/diagram-to-image/scripts/diagram-to-image.mjs --type table -o table.pngStep 5: Report Result
After conversion, tell the user: 1. Full path where image was saved 2. Why that location was chosen (briefly) 3. File size in bytes (printed by the script) 4. Suggest they can specify a different location if needed
Examples
Example 1: Project with images/ directory
Context: User is in a project that has ./images/ directory, discussing authentication.
User: "Convert this to an image"
flowchart TD
A[Login] --> B{Valid?}
B -->|Yes| C[Dashboard]
B -->|No| D[Error]Action: 1. Detect ./images/ exists 2. Analyze content → authentication flow 3. Generate filename: login-flow.png 4. Save content to /tmp/diagram.mmd 5. Run: node ~/.claude/skills/diagram-to-image/scripts/diagram-to-image.mjs /tmp/diagram.mmd -o ./images/login-flow.png
---
Example 2: Writing X article about AI with ocean theme
Context: User mentioned writing an article about AI agents for X.
User: "Make this a PNG with ocean theme"
flowchart LR
User --> Agent --> Tools --> ResponseAction: 1. Save content to /tmp/diagram.mmd 2. Run: node ~/.claude/skills/diagram-to-image/scripts/diagram-to-image.mjs /tmp/diagram.mmd -o ./ai-agent-flow.png --theme ocean
---
Example 3: Data comparison table
User: "Export this table as image"
| Model | Speed | Accuracy |
|-------|-------|----------|
| GPT-4 | Slow | High |
| Claude | Fast | High |Action: 1. Save content to /tmp/table.md 2. Run: node ~/.claude/skills/diagram-to-image/scripts/diagram-to-image.mjs /tmp/table.md -o ./model-comparison.png (auto-detects as table)
---
Example 4: User specifies location
User: "Save this diagram to ~/Desktop/my-chart.png"
Action: Use exactly ~/Desktop/my-chart.png as output path.
Error Handling
- If the API server is unreachable, the script prints a clear error message
- If content type auto-detection fails, use
--type mermaidor--type tableexplicitly - For local development/testing, use
--server http://localhost:3000
#!/usr/bin/env node
import { readFileSync, writeFileSync } from 'node:fs';
const DEFAULTS = {
server: 'https://diagramless.xyz',
scale: 2,
type: 'auto',
theme: 'default',
};
function usage() {
console.log(`Usage: diagram-to-image [input-file] -o <output.png> [options]
Options:
-o, --output <file> Output PNG file (required)
--theme <name> Theme: default, dark, forest, neutral, ocean, emerald, midnight, slate, lavender, blueprint
--type <type> Content type: auto, mermaid, table (default: auto)
--scale <n> Scale factor 1-4 (default: 2)
--bg <color> Background color (default: white)
--server <url> Server URL (default: ${DEFAULTS.server})
-h, --help Show this help
Examples:
diagram-to-image diagram.mmd -o output.png
diagram-to-image table.md -o table.png --type table --theme ocean
echo "graph TD; A-->B" | diagram-to-image -o out.png`);
process.exit(0);
}
// Parse args
const args = process.argv.slice(2);
if (args.length === 0 || args.includes('-h') || args.includes('--help')) usage();
let inputFile = null;
let output = null;
let theme = DEFAULTS.theme;
let type = DEFAULTS.type;
let scale = DEFAULTS.scale;
let bg = 'white';
let server = DEFAULTS.server;
for (let i = 0; i < args.length; i++) {
const arg = args[i];
if (arg === '-o' || arg === '--output') { output = args[++i]; }
else if (arg === '--theme') { theme = args[++i]; }
else if (arg === '--type') { type = args[++i]; }
else if (arg === '--scale') { scale = Number(args[++i]); }
else if (arg === '--bg') { bg = args[++i]; }
else if (arg === '--server') { server = args[++i]; }
else if (!arg.startsWith('-')) { inputFile = arg; }
else { console.error(`Unknown option: ${arg}`); process.exit(1); }
}
if (!output) { console.error('Error: -o/--output is required'); process.exit(1); }
// Read input from file or stdin
let code;
if (inputFile) {
code = readFileSync(inputFile, 'utf-8');
} else if (!process.stdin.isTTY) {
code = readFileSync(0, 'utf-8');
} else {
console.error('Error: provide an input file or pipe content via stdin');
process.exit(1);
}
// POST to server
const url = `${server}/api/render`;
const body = JSON.stringify({ code, theme, type, scale, bg });
try {
const res = await fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body,
});
if (!res.ok) {
const err = await res.json().catch(() => ({ error: res.statusText }));
console.error(`Error ${res.status}: ${err.error || res.statusText}`);
process.exit(1);
}
const buffer = Buffer.from(await res.arrayBuffer());
writeFileSync(output, buffer);
console.log(`Saved ${output} (${buffer.length} bytes)`);
} catch (err) {
console.error(`Failed to connect to ${url}: ${err.message}`);
console.error('Is the diagramless.xyz server reachable?');
process.exit(1);
}
#!/usr/bin/env python3
"""
Convert Markdown table to PNG image.
Usage: python3 table_to_image.py <input.md> <output.png> [--scale 2]
"""
import sys
import re
from pathlib import Path
try:
from PIL import Image, ImageDraw, ImageFont
except ImportError:
print("Error: Pillow not installed. Run: pip install pillow")
sys.exit(1)
def parse_markdown_table(content: str) -> tuple[list[str], list[list[str]], list[str]]:
"""Parse markdown table into headers, rows, and alignments."""
lines = [line.strip() for line in content.strip().split('\n') if line.strip()]
if len(lines) < 2:
raise ValueError("Table must have at least 2 rows")
def parse_cells(line: str) -> list[str]:
line = line.strip()
if line.startswith('|'):
line = line[1:]
if line.endswith('|'):
line = line[:-1]
return [cell.strip() for cell in line.split('|')]
# Find separator line
separator_idx = -1
for i, line in enumerate(lines):
if re.match(r'^\|?[\s]*:?-{2,}:?[\s]*(\|[\s]*:?-{2,}:?[\s]*)*\|?$', line):
separator_idx = i
break
if separator_idx > 0:
# Has headers
headers = parse_cells(lines[separator_idx - 1])
sep_cells = parse_cells(lines[separator_idx])
alignments = []
for cell in sep_cells:
cell = cell.strip()
if cell.startswith(':') and cell.endswith(':'):
alignments.append('center')
elif cell.endswith(':'):
alignments.append('right')
else:
alignments.append('left')
rows = [parse_cells(line) for line in lines[separator_idx + 1:]]
else:
# No headers - all data rows
headers = []
rows = [parse_cells(line) for line in lines]
alignments = ['left'] * (len(rows[0]) if rows else 0)
return headers, rows, alignments
def get_font(size: int, bold: bool = False):
"""Get a font, falling back to default if system fonts unavailable."""
font_paths = [
# macOS
"/System/Library/Fonts/SFNSMono.ttf",
"/System/Library/Fonts/Helvetica.ttc",
"/Library/Fonts/Arial.ttf",
# Linux
"/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
"/usr/share/fonts/TTF/DejaVuSans.ttf",
# Windows
"C:/Windows/Fonts/arial.ttf",
]
for path in font_paths:
try:
return ImageFont.truetype(path, size)
except (OSError, IOError):
continue
# Fallback to default
return ImageFont.load_default()
def render_table_to_image(
headers: list[str],
rows: list[list[str]],
alignments: list[str],
scale: int = 2
) -> Image.Image:
"""Render table data to a PIL Image."""
# Configuration
base_font_size = 14
font_size = base_font_size * scale
padding_x = 16 * scale
padding_y = 12 * scale
border_radius = 8 * scale
margin = 20 * scale
# Colors
bg_color = (255, 255, 255)
header_bg = (249, 250, 251)
text_color = (55, 65, 81)
header_text_color = (17, 24, 39)
border_color = (229, 231, 235)
# Fonts
regular_font = get_font(font_size)
bold_font = get_font(font_size, bold=True)
# Calculate column widths
col_count = len(headers) if headers else (len(rows[0]) if rows else 0)
col_widths = [0] * col_count
# Create temp image for text measurement
temp_img = Image.new('RGB', (1, 1))
temp_draw = ImageDraw.Draw(temp_img)
# Measure headers
for i, header in enumerate(headers):
bbox = temp_draw.textbbox((0, 0), header, font=bold_font)
col_widths[i] = max(col_widths[i], bbox[2] - bbox[0])
# Measure data cells
for row in rows:
for i, cell in enumerate(row):
if i < col_count:
bbox = temp_draw.textbbox((0, 0), cell, font=regular_font)
col_widths[i] = max(col_widths[i], bbox[2] - bbox[0])
# Add padding to widths
col_widths = [w + padding_x * 2 for w in col_widths]
# Calculate dimensions
row_height = font_size + padding_y * 2
header_height = row_height if headers else 0
table_width = sum(col_widths)
table_height = header_height + len(rows) * row_height
img_width = table_width + margin * 2
img_height = table_height + margin * 2
# Create image
img = Image.new('RGB', (img_width, img_height), bg_color)
draw = ImageDraw.Draw(img)
# Draw table border (rounded rectangle)
x0, y0 = margin, margin
x1, y1 = margin + table_width, margin + table_height
draw.rounded_rectangle([x0, y0, x1, y1], radius=border_radius, outline=border_color, width=scale)
y = margin
# Draw header
if headers:
# Header background
draw.rounded_rectangle(
[x0, y0, x1, y0 + row_height],
radius=border_radius,
fill=header_bg
)
# Cover bottom corners of header (they should be square)
draw.rectangle([x0, y0 + row_height - border_radius, x1, y0 + row_height], fill=header_bg)
# Header border
draw.line([(x0, y + row_height), (x1, y + row_height)], fill=border_color, width=scale)
# Header text
x = margin
for i, header in enumerate(headers):
bbox = draw.textbbox((0, 0), header, font=bold_font)
text_width = bbox[2] - bbox[0]
if alignments[i] == 'center':
text_x = x + (col_widths[i] - text_width) // 2
elif alignments[i] == 'right':
text_x = x + col_widths[i] - text_width - padding_x
else:
text_x = x + padding_x
text_y = y + padding_y
draw.text((text_x, text_y), header, fill=header_text_color, font=bold_font)
x += col_widths[i]
y += row_height
# Draw data rows
for row_idx, row in enumerate(rows):
# Row border (except last row)
if row_idx < len(rows) - 1:
draw.line([(x0, y + row_height), (x1, y + row_height)], fill=border_color, width=scale)
# Cell text
x = margin
for i, cell in enumerate(row):
if i >= col_count:
break
bbox = draw.textbbox((0, 0), cell, font=regular_font)
text_width = bbox[2] - bbox[0]
if i < len(alignments):
if alignments[i] == 'center':
text_x = x + (col_widths[i] - text_width) // 2
elif alignments[i] == 'right':
text_x = x + col_widths[i] - text_width - padding_x
else:
text_x = x + padding_x
else:
text_x = x + padding_x
text_y = y + padding_y
draw.text((text_x, text_y), cell, fill=text_color, font=regular_font)
x += col_widths[i]
y += row_height
return img
def main():
if len(sys.argv) < 3:
print("Usage: python3 table_to_image.py <input.md> <output.png> [--scale N]")
sys.exit(1)
input_path = sys.argv[1]
output_path = sys.argv[2]
# Parse optional scale argument
scale = 2
if '--scale' in sys.argv:
scale_idx = sys.argv.index('--scale')
if scale_idx + 1 < len(sys.argv):
try:
scale = int(sys.argv[scale_idx + 1])
except ValueError:
pass
# Read input
content = Path(input_path).read_text()
# Parse table
try:
headers, rows, alignments = parse_markdown_table(content)
except Exception as e:
print(f"Error parsing table: {e}")
sys.exit(1)
if not rows:
print("Error: No data rows found in table")
sys.exit(1)
# Render image
img = render_table_to_image(headers, rows, alignments, scale)
# Save
output = Path(output_path)
img.save(output, 'PNG')
print(f"Saved: {output} ({img.width}x{img.height})")
if __name__ == '__main__':
main()
Related skills
FAQ
What themes does diagram-to-image support?
diagram-to-image supports 10 themes: default, dark, forest, neutral, ocean, emerald, midnight, slate, lavender, and blueprint. Pass --theme to select one when rendering Mermaid or table input to PNG.
What scale range does diagram-to-image accept?
diagram-to-image accepts scale factors from 1 to 4 via the --scale flag, defaulting to 2. Higher scale produces sharper PNG output for README and spec documentation assets.
Is Diagram To Image safe to install?
skills.sh reports 3 of 3 security scanners passed. Review the Security Audits panel on this page before installing in production.