[python]ImageDraw object has no attribute textsize
问题场景:
AttributeError: ‘ImageDraw‘ object has no attribute ‘textsize‘,一般在pillow>=10.0.0以后出现
原因分析
ImageDraw在高版本中移除了textsize函数,高版本中无法直接使用imagedraw.textsize:
textsize is deprecated and will be removed in Pillow 10 (2023-07-01). Use textbbox or textlength instead.
解决方案:
10.0以下版本可以使用:
font = ImageFont.truetype('msyh.ttf', size=45) draw = ImageDraw.Draw(image) w, h = draw.textsize(text, font)
10.0以后版本可以使用代码:
font = ImageFont.truetype('msyh.ttf', size=45) draw = ImageDraw.Draw(image) left, top, right, bottom = font.getbbox(text) w, h = right - left, bottom - top
作者:码农张三疯