You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

使用Pillow给图片添加文字后保存时出现AttributeError: 'ImageDraw' object has no attribute '__array_interface__'错误

Pillow给图片添加文字后保存时出现AttributeError: 'ImageDraw' object has no attribute 'array_interface'错误

这个错误的原因非常明确——你把ImageDraw绘图工具对象当成了PIL Image/numpy数组来使用了,Image.fromarray()根本不接受ImageDraw类型的参数,自然会抛出这个属性不存在的错误。

错误根源分析

你代码里的核心问题出在对象混淆上,我们来拆解错误的步骤:

# 这里你临时创建了一个PIL Image,然后生成了它的Draw绘图对象,但没有保存这个Image的引用
img_pil_4dtxt = ImageDraw.Draw(Image.fromarray(src_img_base))
# 用Draw对象写文字(这一步本身是对的,但你没保留被修改的原始Image)
img_pil_4dtxt.text(textpos, textwrite, font=font, fill=font_color_bgra)
# 致命错误!你把"画笔"对象传给了需要图像/数组的Image.fromarray()
Image.fromarray(img_pil_4dtxt).save(...)

ImageDraw.Draw()的本质是获取一个可以操作PIL Image的绘图工具,它本身不是图像,只是用来在Image上绘图的"画笔"。所有的文字绘制操作都是直接作用在原始PIL Image上的,你需要保留这个Image的引用才能保存修改后的结果。

修正后的正确流程

  1. 先把numpy数组转换成PIL Image对象,并保存这个引用
  2. 基于这个Image创建ImageDraw绘图工具
  3. 用Draw工具在Image上绘制文字
  4. 直接保存经过修改的PIL Image对象(或转成numpy数组用于后续操作)

修正后的完整代码片段

替换你错误的那部分代码:

textpos = (520, 210)    
textwrite = 'Testname'

# 1. 把numpy数组转成PIL Image,保存核心引用
img_pil = Image.fromarray(src_img_base)
# 2. 创建绘图工具Draw
draw = ImageDraw.Draw(img_pil)
# 3. 在Image上写文字:3通道图像用RGB颜色(去掉alpha通道),4通道则保留BGRA
fill_color = font_color_bgra[:3] if len(src_img_base.shape) == 3 and src_img_base.shape[2] ==3 else font_color_bgra
draw.text(textpos, textwrite, font=font, fill=fill_color)

# 4. 用os.path.join安全拼接路径,避免手动加斜杠的问题
save_filename = f'upd_{filename}'
save_path = os.path.join(output_folder_final_path, save_filename)

print('saved img in path:', save_path)
img_pil.save(save_path)
print('saved_img done')

额外优化建议

  • 路径拼接用os.path.join:避免不同操作系统的路径分隔符问题,也能减少手动拼接的拼写错误,比如读取输入图像时也可以优化:
    src_img_path = os.path.join(input_subfolder_path, filename)
    src_img_use = np.array(Image.open(src_img_path))
    
  • 颜色通道匹配:如果使用的是带alpha通道的4通道图像(比如你注释掉的src_img_use),可以直接使用BGRA格式的fill颜色;如果是3通道RGB图像,务必去掉alpha通道,否则可能出现颜色异常。
  • 临时对象不要丢:永远保留被Draw工具操作的原始PIL Image引用,所有绘图修改都是直接作用在这个对象上的。

备注:内容来源于stack exchange,提问作者UserM

火山引擎 最新活动