将 Pillow 从 9.5.0 升级到 10.0.0 或更高版本 - 不会对文本产生相同的结果

问题描述 投票:0回答:1

我尝试将 Pillow lib 从 9.5.0 更新到 10.0.0/10.1.0,并获得了不同的文本创建输出。



您可以看到差异:

根据文档完成需要的修改:

https://pillow.readthedocs.io/en/stable/deprecations.html

附注我正在使用 Mac 和 Python 3.10

我错过了什么?

更新:

我会尽量说得更清楚:

  1. 问题是,在枕头 10.0.0 及更高版本中,我们不能再使用
    textsize
    ,而应该使用
    textbbox
    multiline_textbbox
  2. 我尝试了
    textbbox
    multiline_textbbox
    的不同组合,以获得与
    textsize
    相同的结果,但没有成功。
  3. 为了更容易调试,您也可以在 Pillow 9.5.0 中看到差异。

“旧”代码:

(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

我错过了一些东西,但我不知道是什么。这本来应该是第一个选项,但根本不起作用。

附注文本可以包含多行。

python python-imaging-library
1个回答
0
投票

这是代码,它给出了完全相同的结果:

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
© www.soinside.com 2019 - 2024. All rights reserved.