You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Pillow 10.0.0中ImageDraw无textsize属性及PIL导入失败问题求助

问题解决:自动生成带文字图片的代码错误修复

1. AttributeError: 'ImageDraw' object has no attribute 'textsize'

  • 原因:Pillow 10.0.0版本已移除textsize方法,官方用textbbox替代了它。
  • 解决方式:使用textbbox获取文本的边界框(返回值为(left, top, right, bottom)),再通过计算边界框的差值得到文本宽高。

2. ModuleNotFoundError: No module named 'PIL'

  • 原因:CMD使用的Python环境和Sublime Text的环境不一致,该环境未安装Pillow包。
  • 解决方式:在CMD中执行对应Python版本的安装命令:
    pip install pillow
    # 若系统默认Python为2.x,改用pip3
    pip3 install pillow
    

修正后的完整代码

from PIL import Image, ImageDraw, ImageFont

def metti_testo_su_sfondo(testo, sfondo, colore_testo=(0, 0, 0), dimensione_font=25):
    # 打开背景图片
    immagine_sfondo = Image.open(sfondo)
    disegno = ImageDraw.Draw(immagine_sfondo)
    
    # 加载字体:若系统找不到ARIAL.TTF,替换为完整路径(比如Windows下是"C:/Windows/Fonts/arial.ttf")
    font = ImageFont.truetype("ARIAL.TTF", dimensione_font)
    
    # 用textbbox替代textsize,获取文本边界框
    bbox = disegno.textbbox((0, 0), testo, font=font)
    text_width = bbox[2] - bbox[0]
    text_height = bbox[3] - bbox[1]
    
    # 计算文本居中坐标
    x = (immagine_sfondo.width - text_width) // 2
    y = (immagine_sfondo.height - text_height) // 2
    
    # 绘制文本并保存
    disegno.text((x, y), testo, fill=colore_testo, font=font)
    immagine_sfondo.save("spotted.png")

testo_da_inserire = "Ciao, mondo!"
sfondo_da_utilizzare = "spotted_bianco.jpg" 

metti_testo_su_sfondo(testo_da_inserire, sfondo_da_utilizzare)

额外提示

如果运行时提示找不到字体文件,需将"ARIAL.TTF"替换为系统中Arial字体的实际路径:

  • Windows:C:/Windows/Fonts/arial.ttf
  • macOS:/Library/Fonts/Arial.ttf

内容的提问来源于stack exchange,提问作者carokann17

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 23:25:08