Here in this tutorial I am going to show you how to resize bulk images using Python’s PIL library. The bulk or multiple images which will be resized are kept into a folder. All the image files will be read one by one will be resized to a particular width x height.
You can resize images in Python with the help of PIL (Pillow) and OS library.
You may have a requirement in your application when you need to use multiple images and it may not be a good idea to edit all images manually to set the width and height. So if you write a program that will do the job in few times depending on the number of files are there in the source folder from where your program is going to read them.
Resize Bulk or Multiple Images
In the following example with source code I will show you how to read all the image files from a source directory to resize them one by one.
The resizing will take time depending on the number of image files present in the directory.
While saving the image I am using the image’s original name with a suffix _resized.jpg which will make sure to create a separate image without overwriting the original image.
os.listdir(dir) function, where
dir is the source directory that contains images, you can read all the file names in a directory.
In the following example I am not specifying any parameter, such as, ANTIALIAS, quality, etc.
import PIL import os import os.path from PIL import Image img_dir = r'C:/MyDocuments/roytuts/feature-images/resized-1/' print('Bulk images resizing started...') for img in os.listdir(img_dir): f_img = img_dir + img f, e = os.path.splitext(img_dir + img) img = Image.open(f_img) img = img.resize((1200, 628)) img.save(f + '_resized.jpg') print('Bulk images resizing finished...')
In the following example I am using ANTIALIAS and quality parameters while resizing and saving the image.
In the following code,
Image.ANTIALIAS indicates a high-quality down-sampling filter (best quality). If omitted, or if the image has mode “1” or “P”, it is set
quality parameter indicates the quality of the resized image which is restored during saving to the disk. 100 is the highest possible value for this parameter.
from PIL import Image import os, sys img_dir = "C:/MyDocuments/roytuts/feature-images/resized-2/" dirs = os.listdir( img_dir ) def resize_bulk_images(): for img in dirs: if os.path.isfile(img_dir + img): im = Image.open(img_dir + img) f, e = os.path.splitext(img_dir + img) imResize = im.resize((1200, 628), Image.ANTIALIAS) imResize.save(f + '_resized.jpg', 'JPEG', quality=90) print('Bulk images resizing started...') resize_bulk_images() print('Bulk images resizing finished...')
That’s all. Hope you got an idea how to resize bulk or multiple images from a directory using Python and PIL (Pillow) module.
Thanks for reading.