From fbf8d90063948e0675d4365f28e3e1aa64111665 Mon Sep 17 00:00:00 2001 From: Reedy Date: Tue, 2 Jan 2024 02:46:20 +0000 Subject: [PATCH] captcha(-old).py: Support Pillow 10 getsize() function was removed in version 10 Bug: T354099 Change-Id: I019a5a89de4340d73a938c907c0a6f5cc22a659c --- captcha-old.py | 12 +++++++++++- captcha.py | 12 +++++++++++- 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/captcha-old.py b/captcha-old.py index 358b8e67e..4b94cbf53 100644 --- a/captcha-old.py +++ b/captcha-old.py @@ -46,6 +46,11 @@ except: nonalpha = re.compile('[^a-z]') # regex to test for suitability of words +# Pillow 9.2 added getbbox to replace getsize, and getsize() was removed in Pillow 10 +# https://pillow.readthedocs.io/en/stable/releasenotes/10.0.0.html#font-size-and-offset-methods +# We don't have a requirements.txt, and therefore don't declare any specific supported or min version... +IMAGEFONT_HAS_GETBBOX = hasattr(ImageFont.ImageFont, "getbbox") + # Does X-axis wobbly copy, sandwiched between two rotates def wobbly_copy(src, wob, col, scale, ang): x, y = src.size @@ -79,8 +84,13 @@ def gen_captcha(text, fontname, fontsize, file_name): fgcolor = 0xffffff # create a font object font = ImageFont.truetype(fontname,fontsize) + # determine dimensions of the text - dim = font.getsize(text) + if IMAGEFONT_HAS_GETBBOX: + dim = font.getbbox(text)[2:] + else: + dim = font.getsize(text) + # create a new image significantly larger that the text edge = max(dim[0], dim[1]) + 2*min(dim[0], dim[1]) im = Image.new('RGB', (edge, edge), bgcolor) diff --git a/captcha.py b/captcha.py index fd758bcb5..f85c1539c 100644 --- a/captcha.py +++ b/captcha.py @@ -47,6 +47,11 @@ except: nonalpha = re.compile('[^a-z]') # regex to test for suitability of words +# Pillow 9.2 added getbbox to replace getsize, and getsize() was removed in Pillow 10 +# https://pillow.readthedocs.io/en/stable/releasenotes/10.0.0.html#font-size-and-offset-methods +# We don't have a requirements.txt, and therefore don't declare any specific supported or min version... +IMAGEFONT_HAS_GETBBOX = hasattr(ImageFont.ImageFont, "getbbox") + # Does X-axis wobbly copy, sandwiched between two rotates def wobbly_copy(src, wob, col, scale, ang): x, y = src.size @@ -80,8 +85,13 @@ def gen_captcha(text, fontname, fontsize, file_name): fgcolor = 0xffffff # create a font object font = ImageFont.truetype(fontname,fontsize) + # determine dimensions of the text - dim = font.getsize(text) + if IMAGEFONT_HAS_GETBBOX: + dim = font.getbbox(text)[2:] + else: + dim = font.getsize(text) + # create a new image significantly larger that the text edge = max(dim[0], dim[1]) + 2*min(dim[0], dim[1]) im = Image.new('RGB', (edge, edge), bgcolor)