[英]resizing all images in a folder using PIL
我可以一次調整每個圖像的大小,但是如何以類似的方式調整一個文件夾中的所有圖像的大小呢? 請幫我。
from PIL import Image
from resizeimage import resizeimage
with open('test-image.jpeg', 'r+b') as f:
with Image.open(f) as image:
cover = resizeimage.resize_cover(image, [200, 100])
cover.save('test-image-cover.jpeg', image.format)
只需遍歷當前目錄中的文件
import os
from PIL import Image
from resizeimage import resizeimage
base = '/the/path'
for path in os.listdir(base):
with Image.open(os.path.join(base, path)) as image:
cover = resizeimage.resize_cover(image, [200, 100])
cover.save(path, image.format)
更新:現在使用os.listdir()
代替glob.glob()
因為需要從原始文件生成新文件名。 現在,代碼將調整大小的圖像及其原始文件和添加的后綴保存在同一文件夾中。
請注意, Image.open()
希望將文件路徑傳遞給它,而不是打開的文件。
import os
from PIL import Image
from resizeimage import resizeimage
img_folder = '/path/to/img_folder'
fileext = '.jpg'
suffix = '_RESIZED'
for img_filename in os.listdir(img_folder):
filename, ext = os.path.splitext(img_filename)
if ext == fileext:
print(filename, ext)
src_img_filepath = os.path.join(img_folder, img_filename)
dst_img_filepath = os.path.join(img_folder, filename+suffix, ext)
with Image.open(src_img_filepath) as image:
cover = resizeimage.resize_cover(image, [200, 100])
cover.save(dst_img_filepath, image.format)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.