调整文件夹中的多个图像的大小(Python)

时间:2017-07-24 09:00:55

标签: python resize python-imaging-library

我已经看到了建议的例子,但其中一些没有用。

所以,我有这个代码似乎适用于一个图像:

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....

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

谢谢

3 个答案:

答案 0 :(得分:1)

我假设您要迭代特定文件夹中的图像。

你可以这样做:

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()以使图像名称唯一。这首先是我的想法。你可以做点别的。这是为了不相互覆盖。

答案 1 :(得分:0)

# 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)

答案 2 :(得分:0)

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

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)