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.
Use like this:
./add-image.py ~/Downloads/new-image.svg
Script source code
#!/usr/bin/env python3
from datetime import datetime
import argparse
import os.path
import subprocess
import shutil
from urllib.parse import quote
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", "")
print("Use the image like this:")
print(f"![{caption}](/{fileurl})")
Example output
Adding image to static/images/2024/6/new-image.svg
Use the image like this:
![Caption](/images/2024/6/new-image.svg)
It will also handle special characters like spaces in filenames correctly, example:
Adding image to static/images/2024/9/KiCad No Icons.png
Use the image like this:
![Caption](/images/2024/9/KiCad%20No%20Icons.png)