解决Python PIL ImageDraw 'textsize' 属性错误:获取文本大小
这个错误是因为在ImageDraw对象上没有'textsize'方法。如果你想获取文本的大小,你需要使用PIL库中的ImageFont对象。
你可以按照以下步骤来解决这个问题:
- 确保你已经正确导入了PIL库,包括ImageDraw和ImageFont模块。
from PIL import ImageDraw, ImageFont
- 创建一个ImageFont对象,用于设置字体和大小。
font = ImageFont.truetype('font.ttf', size)
其中,'font.ttf'是你想使用的字体文件的路径,size是你想要的字体大小。
- 使用ImageFont对象的getsize方法来获取文本的大小。
text_size = font.getsize(self.css_icons[icon])
其中,self.css_icons[icon]是你想要获取大小的文本内容。
这样,你就可以得到文本的宽度和高度了。
width, height = text_size
完整的代码示例:
from PIL import ImageDraw, ImageFont
font = ImageFont.truetype('font.ttf', size)
text_size = font.getsize(self.css_icons[icon])
width, height = text_size
希望能帮助到你解决问题!
原文地址: https://www.cveoy.top/t/topic/pc8R 著作权归作者所有。请勿转载和采集!