批量更改图片尺寸是一项常见的任务,比如在创建网站时需要将一组图片的尺寸缩放到相同的比例,或者将数百张图片转换到特定的分辨率。在本文中,我们将从多个方面详细阐述如何使用Python进行批量更改图片尺寸的操作。
一、准备工作
在开始之前,我们需要安装Python中的Pillow库,它提供了Image模块,可以方便地处理图片文件。使用以下命令安装:
pip install pillow
一旦已安装Pillow库,我们就可以开始探索有关如何批量更改图片尺寸的各种方法。
二、使用单个图片进行尺寸更改
在了解如何批量处理图片之前,我们可以先使用单个图片进行尺寸更改的示例。为此,我们将从Image模块导入Image类和ImageFilter子模块。
from PIL import Image
from PIL import ImageFilter
然后,我们可以打开要更改其尺寸的图片并调整其大小。以下代码以将图片的宽度和高度缩小到原始大小的50%为例:
img = Image.open('image.jpg')
new_size = (int(img.size[0] * 0.5), int(img.size[1] * 0.5))
img = img.resize(new_size)
img.save('image_resized.jpg')
此代码将打开名为“image.jpg”的文件并将其缩小到原始尺寸的50%。然后,将保存缩小后的图像为“image_resized.jpg”。可以根据需要修改新图像的大小。
三、批量更改文件夹内所有图片的尺寸
现在,我们来看一下如何使用Python批量更改一个文件夹中所有图片的尺寸。在此示例中,可以将新尺寸设为1000x1000像素。我们将使用os.walk方法在所有子文件夹中查找图片文件,然后更改其大小。
import os
from PIL import Image
def resize_images(directory, new_size):
for root, _, files in os.walk(directory):
for file in files:
if file.endswith('.jpg') or file.endswith('.png'):
img = Image.open(os.path.join(root, file))
img = img.resize(new_size)
img.save(os.path.join(root, f"{os.path.splitext(file)[0]}_resized.jpg"))
此代码将使用以下参数调用resize_images函数:
resize_images('path/to/folder', (1000, 1000))
该函数将遍历路径中的所有文件夹和文件。如果文件是.png或.jpg文件,则将其打开并调整大小,然后保存为新文件“filename_resized.jpg”。
四、保留原始图片的纵横比例
另一种批量更改图像尺寸的方法是保留纵横比例,以确保图像不会变形。对于此任务,我们可以使用以下代码:
import os
from PIL import Image
def resize_images(directory, max_size):
for root, _, files in os.walk(directory):
for file in files:
if file.endswith('.jpg') or file.endswith('.png'):
img = Image.open(os.path.join(root, file))
img.thumbnail(max_size, Image.ANTIALIAS)
img.save(os.path.join(root, f"{os.path.splitext(file)[0]}_resized.jpg"))
在以上代码中,我们定义了max_size变量,该变量指定了图像的最大尺寸,以保持其纵横比例。我们使用thumbnail函数将较大的图像缩小到max_size尺寸并将其保存在特定位置。
五、使用命令行进行图像调整
如果您更喜欢使用命令行来调整图像的大小,那么可以使用Python的argparse模块创建一个简单的命令行界面。以下代码将允许用户指定要调整大小的文件夹和新的图像大小:
import os
import argparse
from PIL import Image
def resize_images(directory, new_size):
for root, _, files in os.walk(directory):
for file in files:
if file.endswith('.jpg') or file.endswith('.png'):
img = Image.open(os.path.join(root, file))
img = img.resize(new_size)
img.save(os.path.join(root, f"{os.path.splitext(file)[0]}_resized.jpg"))
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Resize images in directory')
parser.add_argument('directory', help='directory containing images to resize')
parser.add_argument('--width', type=int, default=1000,
help='new width of images in pixels (default: %(default)d)')
parser.add_argument('--height', type=int, default=1000,
help='new height of images in pixels (default: %(default)d)')
args = parser.parse_args()
directory = args.directory
new_size = (args.width, args.height)
resize_images(directory, new_size)
从命令行运行此代码时,您可以指定要调整大小的文件夹以及新的图像大小。例如:
python resize_images.py path/to/folder --width 800 --height 600
以上将会调整文件夹中的图像大小,使它们的宽度为800像素,高度为600像素。