From 82c1c1b1eaa0cb0198481e7c9824f1b08ef0d6e3 Mon Sep 17 00:00:00 2001 From: James Vasile <james@jamesvasile.com> Date: Sun, 21 May 2023 23:03:26 -0400 Subject: [PATCH] Add helper for making image sets --- bin/img-srcset | 61 ++++++++++++++++++++++++++++++++++++++++++++ requirements-dev.txt | 1 + requirements.txt | 1 + 3 files changed, 63 insertions(+) create mode 100755 bin/img-srcset diff --git a/bin/img-srcset b/bin/img-srcset new file mode 100755 index 0000000..16de08d --- /dev/null +++ b/bin/img-srcset @@ -0,0 +1,61 @@ +#!/usr/bin/env python3 + +""" +Generate srcset images so we can do something like: + <img src="img.png" width="4000" height="3000" alt="" srcset="img.png 4000w, + img-2000x1500.png 2000w, + img-1024x768.png 1024w, + img-768x576.png 768w, + img-300.png 225w" + sizes = "100vw"> +""" + +import os +from PIL import Image +import sys + +def get_html_dir(curr:str="", token:str="content"): + curr = curr or os.getcwd() + ret = [] + while curr != '/': + curr, child = os.path.split(curr) + if child == token: + break + ret.append(child) + ret.reverse() + return '/' + '/'.join(ret) + + while current_dir != '/': + dir_name = os.path.basename(current_dir) + if target_string in dir_name: + break + current_dir = os.path.dirname(current_dir) + +in_fname = sys.argv[1] +html_dir = get_html_dir() +fname_parts = os.path.splitext(in_fname) +image = Image.open(in_fname) +widths = (4000,2000,1024,768,300) + +## Write files of different widths +print(f'<img src="{html_dir}/{in_fname}"') +print(f' width="{image.width}" height="{image.height}" alt=""') +print(f' srcset="{html_dir}/{in_fname} {image.width}w,') +for width in widths: + if width >= image.width: + continue + height = int((width * image.height) / image.width) + resized_image = image.resize((width, height)) + + ## Write resized image + out_fname = f"{fname_parts[0]}-{width}x{height}{fname_parts[1]}" + resized_image.save(out_fname) + + ## Print html snippet + sys.stdout.write(f' {html_dir}/{out_fname} {width}w') + if width == widths[-1]: + print('" ') + else: + print(', ') +print(' sizes = "100vw">') + diff --git a/requirements-dev.txt b/requirements-dev.txt index ccca182..fe91dd3 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -3,3 +3,4 @@ psutil bs4 pytest-xprocess feedparser +types-Pillow diff --git a/requirements.txt b/requirements.txt index 240339a..092b4a5 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,2 +1,3 @@ pelican[markdown] pelican-search +Pillow -- GitLab