我想运行一个脚本,逐个浏览目录中的 jpg,获取图像中心的一个小正方形剪辑(例如 100x100 像素),并将该正方形保存在第二个目录中作为新目录图像。
执行速度并不重要。只是寻找一种方法来轻松完成此任务,最好不需要安装任何我还没有的东西,并且使用我有时使用的工具或语言(最好是 Python 或 Javascript)。
你会如何完成这样的任务?
这是一个可以完成您想要的操作的 Python 脚本。您需要先使用命令
pip install Pillow
: 安装 Pillow
from PIL import Image
import os
def crop_center(image, width, height):
img_width, img_height = image.size
left = (img_width - width) // 2
top = (img_height - height) // 2
right = (img_width + width) // 2
bottom = (img_height + height) // 2
return image.crop((left, top, right, bottom))
def process_images(input_dir, output_dir):
if not os.path.exists(output_dir):
os.makedirs(output_dir)
for filename in os.listdir(input_dir):
if filename.endswith('.jpg'):
input_path = os.path.join(input_dir, filename)
output_path = os.path.join(output_dir, filename)
with Image.open(input_path) as img:
cropped_img = crop_center(img, 100, 100)
cropped_img.save(output_path)
if __name__ == "__main__":
input_directory = "/path/to/input/directory" # Update this to your input directory
output_directory = "/path/to/output/directory" # Update this to your output directory
process_images(input_directory, output_directory)
process_images()
函数遍历给定input_dir
文件夹中的所有图像,将crop_center()
函数应用于每个图像并将其保存到给定的output_dir
文件夹(如果该文件夹不存在,则会创建它) .