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

zed5wv10  于 11个月前  发布在  Python
关注(0)|答案(1)|浏览(407)

我尝试将Pillow lib从9.5.0更新到10.0.0/ 10.1.0,但文本创建的输出不同。
**您可以看到差异:**x1c 0d1x
根据文档进行所需的更改:

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




我正在使用Mac和Python 3.10
我错过了什么?

更新:

我试着说得更清楚些:
1.问题是,在pillow 10.0.0及以上版本中,我们不能再使用textsize,而应该使用textbboxmultiline_textbbox
1.我尝试了textbboxmultiline_textbbox的不同组合,以实现与textsize相同的结果,但没有成功。
1.为了使调试更容易,您可以在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


我错过了一些东西,我不知道是什么。这应该是第一个选择,但它根本不起作用。
p.s.文本可以包含多行。

dy2hfwbg

dy2hfwbg1#

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

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

字符串

相关问题