1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
|
#!/usr/bin/env python3
# encoding: utf-8
# SPDX-License-Identifier: BSD-3-Clause
from PIL import Image, ImageFont, ImageDraw
import sys
import os
# create_caption.py <background_image> <title?> <phase?> <outfile>
font = ImageFont.load_default()
txt1 = "© 2001-2024"
txt2 = os.environ["VERSION"]
background_image = Image.open(sys.argv[1])
background_image.load()
background_image = background_image.convert("RGBA")
image = Image.new("RGBA", background_image.size, (0, 0, 0, 0))
draw = ImageDraw.Draw(image)
# Getting the text size is tricky since for newer PIL, such as 10.0.0, only
# textbbox() is supported, but for older PIL, such 7.2.0, only textsize()
# is supported. The solution is to default to the newer API, but fallback to
# the older one when it is not available.
try:
# This newer API returns a four item tuple. The "xy" kwarg is returned in
# the first two items, and last two items is the size needed, but with "xy"
# added, so passing "(0, 0)" returns the size needed.
txt1_size = draw.textbbox(xy=(0, 0), text=txt1, font=font)[2:]
txt2_size = draw.textbbox(xy=(0, 0), text=txt2, font=font)[2:]
except:
# This older API simply returns the size needed.
txt1_size = draw.textsize(txt1, font=font)
txt2_size = draw.textsize(txt2, font=font)
draw.text(
(5, int(image.height - txt1_size[1] - 5)),
txt1,
font=font,
fill=(255, 165, 0, 255),
)
draw.text(
(
int(image.width - txt2_size[0] - 10),
int(image.height - txt2_size[1] - 5),
),
txt2,
font=font,
fill=(255, 165, 0, 255),
)
if len(sys.argv) > 3:
# paste the other stuff onto the thing.
logo = Image.open(sys.argv[2])
logo.load()
phase = Image.open(sys.argv[3])
phase.load
image.paste(logo, ((int(image.width / 2) - int(logo.width / 2), 18)))
image.paste(
phase,
(
(int(image.width / 2) - int(phase.width / 2)),
int(image.height - phase.height - 30),
),
)
outfile_name = sys.argv[4]
else:
outfile_name = sys.argv[2]
image = Image.alpha_composite(background_image, image)
image.save(outfile_name)
|