I made a script that loops through an Excel table which looks like this:
item | name | namefontsize | country | code |
---|---|---|---|---|
sample.jpg | Apple | 142 | US | 1564 |
sample2.jpg | Orange | 142 | US | 1562 |
then loops through a folder of .jpg
images.
When it matches it writes some text on the image and saves it as a new one.
How do complete this loop so that it uses the data from columns 2, 3, 4, and 5 in the place of the variables txt1
, txt2
, txt3
, fontsize
, etc. when the image names match?
I'm a newbie so feel free to point out how ugly my code is.
import os
from PIL import Image,ImageFont,ImageDraw, features
import pandas as pd
path='./'
txt1= "name..."
W1 = 1200
H1 = 200
fontSize1 = 142
txt2= "country..."
W2 = 1200
H2 = 400
fontSize2 = 132
txt3= "code..."
W3 = 1200
H3 = 600
fontSize3 = 124
def setText(name,file,txt,fontSize,w,h):
arial = ImageFont.truetype(r'./font.ttf', fontSize)
draw = ImageDraw.Draw(file)
draw.text((w, h), txt, font=arial, fill='#ff0000',
direction="rtl",align="right",anchor="rm",features='rtla')
file.save(f'done {name}')
df = pd.read_excel (r'./data.xlsx')
files = []
for (dirpath, dirnames, filenames) in os.walk(path):
files.extend(filenames)
items= []
for index, row in df.iterrows():
items.append(row["item"])
for i in items:
if i in files:
imageName = i
imgfile = Image.open(f"./{imageName}")
setText(imageName,imgfile,txt1,fontSize1,W1,H1)
setText(imageName,imgfile,txt2,fontSize2,W2,H2)
setText(imageName,imgfile,txt3,fontSize3,W3,H3)