You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

64 lines
2.1 KiB

"""An elementary Web gallery generator using Masonry and Lightbox."""
import json
import os
from argparse import ArgumentParser
from PIL import Image
SUPPORTED_TYPES = ("jpg", "jpeg", "png", "gif", "webp")
def main():
ap = ArgumentParser(description="Generate JSON metadata from images.")
ap.add_argument("dir", help="directory with the images to use")
ap.add_argument("--no-thumbnails", action="store_true", help="disable thumbnail generation")
args = ap.parse_args()
gen_gallery(args.dir, not bool(args.no_thumbnails))
def gen_gallery(dir_path: str, generate_thumbnails: bool = True):
"""Generate the JSON metadata for the images found at dirpath."""
entries = []
for file_name in sorted(os.listdir(dir_path)):
name, ext = os.path.splitext(file_name)
if name.endswith("_t"): # do not add already generated thumbnails
continue
if ext[1:].lower() not in SUPPORTED_TYPES:
continue
image = Image.open(os.path.join(dir_path, file_name))
dimensions = image.size
entry = {
"src": file_name,
"w": dimensions[0],
"h": dimensions[1],
"title": "",
}
if generate_thumbnails:
try:
entry["thumb"] = gen_thumbnail(image, file_name, dir_path)
except OSError as exc:
exit(f"Can't create thumbnail: {exc}")
entries.append(entry)
try:
with open(os.path.join(dir_path, "data.json"), "wt") as data_file:
json.dump(entries, data_file)
except OSError as exc:
exit(f"Can't write data.json file: {exc}")
print("Data JSON saved.")
def gen_thumbnail(image: Image.Image, file_name: str, dir_path: str) -> str:
"""Generate a thumbnail from this image, return its name."""
thumbnail = image.copy()
thumbnail.thumbnail((360, 720), resample=Image.Resampling.LANCZOS)
name, ext = os.path.splitext(file_name)
thumbnail_file_name = name + "_t" + ext
thumbnail_path = os.path.join(dir_path, thumbnail_file_name)
thumbnail.save(thumbnail_path)
return thumbnail_file_name
if __name__ == "__main__":
main()