我尝试将 Pillow lib 从 9.5.0 更新到 10.0.0/10.1.0,并获得了不同的文本创建输出。
根据文档完成需要的修改:
https://pillow.readthedocs.io/en/stable/deprecations.html
附注我正在使用 Mac 和 Python 3.10
我错过了什么?
更新:
我会尽量说得更清楚:
textsize
,而应该使用 textbbox
或 multiline_textbbox
。textbbox
或multiline_textbbox
的不同组合,以获得与textsize
相同的结果,但没有成功。“旧”代码:
(width, height) = draw.textsize(text, font=font)
简化示例:
“新”代码(选项1):
left, top, right, bottom = draw.textbbox((0, 0), text, font)
width, height = right - left, bottom - top
“新”代码(选项2):
left, top, right, bottom = draw.textbbox((0, 0), text, font)
width, height = right, bottom
“新”代码(选项3):
left, top, right, bottom = draw.textbbox((0, 0), text, font)
y_offset_to_remove = top if "\n" in text else 0
width, height = right, bottom - y_offset_to_remove
我错过了一些东西,但我不知道是什么。这本来应该是第一个选项,但根本不起作用。
附注文本可以包含多行。
这是代码,它给出了完全相同的结果:
def _get_text_size(draw: ImageDraw.ImageDraw, text: str, font: ImageFont.ImageFont, spacing: int = 4) -> typing.Tuple[int, int]:
_, _, right, bottom = draw.textbbox((0, 0), text, font=font, anchor='la', spacing=spacing)
if '\n' in text:
line_count = len(text.split('\n'))
_, line_height = _get_text_size(draw, 'A', font=font, spacing=spacing)
return right, line_count * (line_height + spacing) - spacing
return right, bottom