VS Code Task Automation for Markdown to HTML Image Conversion
Background
When preparing content for platforms like CSDN, external image links often need conversion to inline HTML format. This post documents a VS Code task configuration that automates this conversion process.
VS Code Task Setup
Open the command palette and run Tasks: Configure Task to create the following configuration:
{
"version": "2.0.0",
"tasks": [
{
"label": "markdown-image-converter",
"type": "shell",
"command": "python",
"args": [
"D:\\Scripts\\md_to_html.py",
"${file}"
],
"problemMatcher": [],
"group": {
"kind": "build",
"isDefault": true
}
}
]
}
Python Conversion Script
import re
import sys
input_file = sys.argv[1]
with open(input_file, 'r', encoding='utf-8') as f:
original_text = f.read()
pattern = r'!\[(.*?)\]\((.*?)\)'
converted_text = re.sub(pattern, r'<img src="\2" alt="\1"/>', original_text)
with open(input_file, 'w', encoding='utf-8') as f:
f.write(converted_text)
print(f"Converted: {input_file}")
The script uses re.sub() with capturing groups to transform Markdown image syntax into HTML <img> tags. Group \1 captures the alt text, and group \2 captures the image URL.
Workflow
- Open the Markdown file in VS Code
- Trigger the command palette (
Ctrl+Shift+P) - Execute
Tasks: Run Taskand selectmarkdown-image-converter - The script transforms all Markdown images to HTML format in place
This automation eliminates manual find-and-replace operasions, streamlining the content preparation workflow for platforms requiring HTML image embedding.