Hugo 脚本:轻松为博客添加图片
此脚本可用于自动将图片复制到 static 目录并为其生成正确的 markdown。
如果安装了 pyperclip 模块,它还会将 markdown 复制到剪贴板以便轻松粘贴。
使用方式如下:
add_image_usage.sh
./add-image.py ~/Downloads/new-image.svg脚本源代码
add_image.py
#!/usr/bin/env python3
from datetime import datetime
import argparse
import os.path
import subprocess
import shutil
from urllib.parse import quote
try:
import pyperclip
except ImportError:
pyperclip = None
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Create a new post")
parser.add_argument("imagefile", help="The image to import")
args = parser.parse_args()
now = datetime.now()
canonical_image_filename = os.path.basename(args.imagefile)
filename_url_encoded = quote(canonical_image_filename)
# Compute filepaths in the images directory
dirpath = os.path.join("static", "images", f"{now.year}", f"{now.month}")
filepath = os.path.join(dirpath, canonical_image_filename)
filepath_url_encoded = os.path.join(dirpath, filename_url_encoded)
print(f"Adding image to {filepath}")
os.makedirs(os.path.dirname(filepath), exist_ok=True)
shutil.copy(args.imagefile, filepath)
# Add to git
subprocess.run(["git", "add", filepath], check=True)
# User guidance on how to use the path
fileurl = filepath_url_encoded.partition("/")[-1]
caption = canonical_image_filename.replace("_", " ").replace("-", " ").replace(".png", "")
markdown = f""
print("Use the image like this:")
print(markdown)
# Copy to clipboard
if pyperclip:
pyperclip.copy(markdown)
print("Markdown copied to clipboard.")
else:
print("pyperclip not installed. Install with: pip install pyperclip")示例输出
add_image_output.txt
Adding image to static/images/2024/6/new-image.svg
Use the image like this:

Markdown copied to clipboard.它还会正确处理文件名中的特殊字符(如空格),例如:
add_image_output_spaces.txt
Adding image to static/images/2024/9/KiCad No Icons.png
Use the image like this:

Markdown copied to clipboard.If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow