调整文件夹中多张图片的大小 (Python)

Resize multiple images in a folder (Python)

我已经看到建议的示例,但其中一些不起作用。

所以,我有这个代码,它似乎对一张图片工作正常:

im = Image.open('C:\Users\User\Desktop\Images\2.jpg') # image extension *.png,*.jpg
new_width  = 1200
new_height = 750
im = im.resize((new_width, new_height), Image.ANTIALIAS)
im.save('C:\Users\User\Desktop\resized.tif') # .jpg is deprecated and raise error....

如何迭代它并调整多张图片的大小?需要保持纵横比。

谢谢

我假设您想遍历特定文件夹中的图像。

你可以这样做:

import os
from datetime import datetime

for image_file_name in os.listdir('C:\Users\User\Desktop\Images\'):
    if image_file_name.endswith(".tif"):
        now = datetime.now().strftime('%Y%m%d-%H%M%S-%f')

        im = Image.open('C:\Users\User\Desktop\Images\'+image_file_name)
        new_width  = 1282
        new_height = 797
        im = im.resize((new_width, new_height), Image.ANTIALIAS)
        im.save('C:\Users\User\Desktop\test_resize\resized' + now + '.tif')

datetime.now() 只是为了使图像名称唯一。这只是我首先想到的一个 hack。你可以做点别的。这是为了不相互覆盖所必需的。

# Resize all images in a directory to half the size.
#
# Save on a new file with the same name but with "small_" prefix
# on high quality jpeg format.
#
# If the script is in /images/ and the files are in /images/2012-1-1-pics
# call with: python resize.py 2012-1-1-pics

import Image
import os
import sys

directory = sys.argv[1]

for file_name in os.listdir(directory):
print("Processing %s" % file_name)
image = Image.open(os.path.join(directory, file_name))

x,y = image.size
new_dimensions = (x/2, y/2) #dimension set here
output = image.resize(new_dimensions, Image.ANTIALIAS)

output_file_name = os.path.join(directory, "small_" + file_name)
output.save(output_file_name, "JPEG", quality = 95)

print("All done")

上面写着

new_dimensions = (x/2, y/2)

您可以设置任何您想要的维度值 例如,如果您想要 300x300,则将代码更改为下面的代码行

new_dimensions = (300, 300)

我假设您在某个文件夹中有一个图像列表,并且您要调整所有图像的大小

from PIL import Image
import os

    source_folder = 'path/to/where/your/images/are/located/'
    destination_folder = 'path/to/where/you/want/to/save/your/images/after/resizing/'
    directory = os.listdir(source_folder)
    
    for item in directory:
        img = Image.open(source_folder + item)
        imgResize = img.resize((new_image_width, new_image_height), Image.ANTIALIAS)
        imgResize.save(destination_folder + item[:-4] +'.tif', quality = 90)