所以這裏是我的困境......我正在編寫一個腳本,它從文件夾中讀取所有.png文件,然後將它們轉換爲多個不同的維度這是我在列表中指定的。一切工作,因爲它應該除了它處理完一個圖像後退出。如何通過zip()函數的兩個元素循環兩次 - Python
這裏是我的代碼:
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)
如果目標文件夾包含2個圖像稱爲image1.png,image2.png(用於可視化的緣故,我要補充的是得到應用的尺寸下將返回爲下劃線之後的圖像):
image1_1024x1024.png, .............., image1_640x690.png(返回image1的細所有7周不同的尺寸)
它在我需要時停在那裏它將相同的轉換應用於image_2。我知道這是因爲widthList和heightList的長度只有7個元素,所以在image2輪到它之前退出循環。有沒有什麼辦法可以通過widthList和heightList爲targetPath中的每個圖像循環?
這是有幫助爲了獲得寬度和高度分開,但它並沒有幫助解決我遇到的實際問題,這是獲取目標文件夾中的每個圖像貼上的那些屬性 – Coletrain
啊,我的確覆蓋了文件!添加一點點消息來生成獨特的名稱,並按預期工作。非常感謝您的輸入我很感激 – Coletrain