diff --git a/modules/images.py b/modules/images.py index 4565a7ee..5f0c136b 100644 --- a/modules/images.py +++ b/modules/images.py @@ -13,6 +13,8 @@ import numpy as np import piexif import piexif.helper from PIL import Image, ImageFont, ImageDraw, ImageColor, PngImagePlugin, ImageOps +from PIL import __version__ as pillow_version +from pkg_resources import parse_version # pillow_avif needs to be imported somewhere in code for it to work import pillow_avif # noqa: F401 import string @@ -168,9 +170,18 @@ def draw_grid_annotations(im, width, height, hor_texts, ver_texts, margin=0): for line in lines: fnt = initial_fnt fontsize = initial_fontsize - while drawing.multiline_textsize(line.text, font=fnt)[0] > line.allowed_width and fontsize > 0: - fontsize -= 1 - fnt = get_font(fontsize) + if parse_version(pillow_version) >= parse_version('10.0.0'): + # New code for Pillow 10.0.0+ + text_width, text_height = drawing.multiline_textbbox((0, 0), line.text, font=fnt)[2:] + while text_width > line.allowed_width and fontsize > 0: + fontsize -= 1 + fnt = get_font(fontsize) + text_width, text_height = drawing.multiline_textbbox((0, 0), line.text, font=fnt)[2:] + else: + # Old code for Pillow versions below 10.0.0 + while drawing.multiline_textsize(line.text, font=fnt)[0] > line.allowed_width and fontsize > 0: + fontsize -= 1 + fnt = get_font(fontsize) drawing.multiline_text((draw_x, draw_y + line.size[1] / 2), line.text, font=fnt, fill=color_active if line.is_active else color_inactive, anchor="mm", align="center") if not line.is_active: