Hugo script to easily add images to your blog

This script can be used to automatically copy images to the static directory and generate the correct markdown for them.

If the pyperclip module is installed, it will also copy the markdown to the clipboard for easy pasting.

Use like this:

example.sh
./add-image.py ~/Downloads/new-image.svg

Script source code

example.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"![{caption}](/{fileurl})"
    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")

Example output

example.txt
Adding image to static/images/2024/6/new-image.svg
Use the image like this:
![Caption](/images/2024/6/new-image.svg)
Markdown copied to clipboard.

It will also handle special characters like spaces in filenames correctly, example:

example.txt
Adding image to static/images/2024/9/KiCad No Icons.png
Use the image like this:
![Caption](/images/2024/9/KiCad%20No%20Icons.png)
Markdown copied to clipboard.

Check out similar posts by category: Hugo, Python