Pillow 10+中替换ImageFont.getsize(text)为textbbox(text)的简便方法
Pillow 10+ 替代弃用的getsize()方法方案
Pillow 10版本之前,可通过getsize()方法获取文本的宽高,但10及以上版本中该方法已被弃用。只需添加两行计算代码,就能用getbbox()方法完成替代。
以下是完整的兼容示例代码:
import streamlit as st from PIL import Image, ImageFont, ImageDraw def text_on_image(image, text, font_size, color): # 加载本地字体文件,需确保字体文件与脚本同目录 font = ImageFont.truetype("Roboto-Regular.ttf", font_size) img = Image.open(image) draw = ImageDraw.Draw(img) image_width, image_height = img.size # 旧版本写法(Pillow <10) # text_width, text_height = font.getsize(text) # Pillow 10+ 兼容写法 left, top, right, bottom = font.getbbox(text) text_width = right - left text_height = bottom - top draw.text( ((image_width - text_width) / 2, (image_height - text_height) / 2), text, fill=color, font=font ) img.save('last_image.jpg')
内容的提问来源于stack exchange,提问作者Ricardo Barcellos
相关产品推荐
相关产品推荐

