Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to loop through one element of a zip() function twice - Python

So here's my dilema... I'm writing a script that reads all .png files from a folder and then converts them to a number of different dimensions which I have specified in a list. Everything works as it should except it quits after handling one image.

Here is my code:

sizeFormats = ["1024x1024", "114x114", "40x40", "58x58", "60x60", "640x1136", "640x960"]

def resizeImages():

widthList = []
heightList = []
resizedHeight = 0
resizedWidth = 0

#targetPath is the path to the folder that contains the images
folderToResizeContents = os.listdir(targetPath)

#This splits the dimensions into 2 separate lists for height and width (ex: 640x960 adds
#640 to widthList and 960 to heightList
for index in sizeFormats:
    widthList.append(index.split("x")[0])
    heightList.append(index.split("x")[1])

#for every image in the folder, apply the dimensions from the populated lists and save
for image,w,h in zip(folderToResizeContents,widthList,heightList):
    resizedWidth = int(w)
    resizedHeight = int(h)
    sourceFilePath = os.path.join(targetPath,image)
    imageFileToConvert = Image.open(sourceFilePath)
    outputFile = imageFileToConvert.resize((resizedWidth,resizedHeight), Image.ANTIALIAS)
    outputFile.save(sourceFilePath)

The following will be returned if the target folder contains 2 images called image1.png,image2.png (for sake of visualization I'll add the dimensions that get applied to the image after an underscore):

image1_1024x1024.png, .............., image1_640x690.png (Returns all 7 different dimensions for image1 fine)

it stops there when I need it to apply the same transformations to image_2. I know this is because the length of widthList and heightList are only 7 elements long and so exits the loop before image2 gets its turn. Is there any way I can go about looping through widthList and heightList for every image in the targetPath?

like image 943
Coletrain Avatar asked Oct 04 '22 17:10

Coletrain


1 Answers

Why not keep it simple:

for image in folderToResizeContents:
    for fmt in sizeFormats:
        (w,h) = fmt.split('x')

N.B. You are overwriting the files produced as you are not changing the name of the outpath.

like image 129
Steve Barnes Avatar answered Oct 07 '22 17:10

Steve Barnes