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