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