首页 > 解决方案 > 如何使用 Python 将文本添加到多个图像

问题描述

我是使用 Python 的新手,我有一个无法解决的问题。我要做的是从包含三列(分别为图像地址、文本 1 和文本 2)的 excel 电子表格中,代码应选择第一个图像,然后插入属于其行的文本 1 和 2 . 我能够完成单个图像的代码,但是当我尝试处理所有图像时遇到问题。

import pandas as pd
from PIL import ImageFont
from PIL import Image
from PIL import ImageDraw

ruta_excel = pd.read_excel('C:/Users/san_2/Documents/Script/ARCPY/Direc.xls',
                           sheet_name=0)
ruta = ruta_excel.iat[0, 0]

image_files = Image.open(ruta)
font_type = ImageFont.truetype('C:/Windows.old/Windows/Fonts/Arial.ttf',18)
draw = ImageDraw.Draw(image_files)
draw.text(xy=(20, 550), text=ruta_excel.iat[0, 1], fill=(255, 255, 255),
          font=font_type)
draw.text(xy=(20, 570), text=ruta_excel.iat[0, 2], fill=(255, 255, 255),
          font=font_type)

image_files.save(ruta, 'JPEG', quality=90)

谢谢

标签: pythonpython-3.xpandasloopspython-imaging-library

解决方案


我不知道PIL,但如果您的代码适用于第一个图像并且您的问题是迭代,那么您可以这样做:

import pandas as pd
from PIL import ImageFont
from PIL import Image
from PIL import ImageDraw

ruta_excel=pd.read_excel('C:/Users/san_2/Documents/Script/ARCPY/Direc.xls',sheet_name=0)
# iterate over rows with itertuples
for row in ruta_excel.itertuples(index=False):
    print (row) # to help you see what is happening but not necessary after
    # row is tuple, doing row[0] access to the first item (the first column)
    ruta=row[0]
    image_files = Image.open(ruta)
    font_type = ImageFont.truetype('C:/Windows.old/Windows/Fonts/Arial.ttf',18)
    draw = ImageDraw.Draw(image_files)
    # here you use row[1] and row[2]
    draw.text(xy=(20,550),text= row[1],fill=(255,255,255),font=font_type)
    draw.text(xy=(20,570),text= row[2],fill=(255,255,255),font=font_type)

    image_files.save(ruta, 'JPEG', quality=90)

推荐阅读