python - 如何使用 Python 将文本添加到多个图像

标签 python python-3.x pandas loops python-imaging-library

我是 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)

谢谢

最佳答案

我不知道 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)

关于python - 如何使用 Python 将文本添加到多个图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50661910/

相关文章:

python-3.x - 从列表中的元素中删除尾随空格

python-3.x - 加快 Keras 中模型的加载速度?

python - 替换日期大于其他日期的 DateTime 列值

python - 如何在系列的多个条件下将值设置为 np.nan?

python - 值错误 : Cannot assign in django

python - 有没有办法用 matplotlib 或任何其他库绘制 3D 饼图?

python - Tornado x-www-form-urlencoded 主体无效 : 'latin-1' codec can't encode characters in position 774-777: ordinal not in range(256)

python - 使用 Pandas 处理 CSV 文件,并将处理后的文件的输出与现有文件进行比较

python - 获取许多一维数组的特征值的最快方法

python autopy问题/困惑