所以这是我的困境......我正在编写一个脚本,从文件夹中读取所有.png文件,然后将它们转换为我在列表中指定的许多不同维度。除了在处理一个图像后退出,一切都按预期工作。
这是我的代码:
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转向之前退出循环。有什么方法可以为targetPath中的每个图像循环遍历widthList和heightList吗?
答案 0 :(得分:3)
为什么不保持简单:
for image in folderToResizeContents:
for fmt in sizeFormats:
(w,h) = fmt.split('x')
<强> N.B。您正在覆盖生成的文件,因为您没有更改路径的名称。
答案 1 :(得分:0)
嵌套for循环,您可以将所有7个维度应用于每个图像
for image in folderToResizeContents:
for w,h in zip(widthList,heightList):
第一个for循环将确保每个图像都会发生,而第二个for循环将确保将图像调整为每个尺寸
答案 2 :(得分:0)
您需要为每个文件重复遍历sizeFormats。 Zip不会这样做,除非你用高度和宽度的循环迭代器变得更加棘手。
当一些嵌套的for循环工作正常时,有时像zip这样的工具会使代码更复杂。我认为它更直接而不是拆分成多个列表然后再将它们拉回来。
sizeFormats = ["1024x1024", "114x114", "40x40", "58x58", "60x60", "640x1136", "640x960"]
sizeTuples = [(int(w), int(h)) for w,h in map(lambda wh: wh.split('x'), sizeFormats)]
def resizeImages():
#for every image in the folder, apply the dimensions from the populated lists and save
for image in os.listdir(targetPath):
for resizedWidth, resizedHeight in sizeTuples:
sourceFilePath = os.path.join(targetPath,image)
imageFileToConvert = Image.open(sourceFilePath)
outputFile = imageFileToConvert.resize((resizedWidth,resizedHeight), Image.ANTIALIAS)
outputFile.save(sourceFilePath)