By compressing (or resizing) the images on your website, you can decrease the load time of your website. Hence you might already know about resizing images for your website and want to do the same thing with python. I will be going over how you can use python to automate this process of resizing images. We will use python to create a program to resize an image based on a specific width/ height. Code snippets below will do the job if you have python installed on your device.
Compress And Rename
import PIL
from PIL import Image
import os
path = 'C:\\Users\\jim\\Documents\\3DPICTURES\\'
export_path = 'C:\\Users\\jim\\Documents\\resized\\'
images = os.listdir(path)
collection ='your-collection-name'
def opt():
for index, image in enumerate(images):
image_name = image.rsplit('.',1)[0]
image = Image.open(path+image)
image.save(export_path+collection+str(index)+'.webp', 'webp', optimize=True, quality=90)
opt()
Compress And Resize To Specific Width And Height
import PIL
from PIL import Image
import os
path = 'C:\\Users\\jim\\Documents\\3DPICTURES\\'
export_path = 'C:\\Users\\jim\\Documents\\resized\\'
images = os.listdir(path)
collection ='your-collection-name'
def resize():
for index, image in enumerate(images):
width = 1920
height = 1080
image = Image.open(path+image)
image = image.resize((width , height))
image.save(export_path+collection+str(index)+'.webp', 'webp', optimize=True, quality=90)
resize()
Compress And Resize To Specific Height
import PIL
from PIL import Image
import os
path = 'C:\\Users\\jim\\Documents\\3DPICTURES\\'
export_path = 'C:\\Users\\jim\\Documents\\resized\\'
images = os.listdir(path)
collection ='Your-collection-name'
def resize():
for index, image in enumerate(images):
fixed_height = 1080
image = Image.open(path+image)
height_percent = (fixed_height / float(image.size[1]))
width_size = int((float(image.size[0]) * float(height_percent)))
image = image.resize((width_size , fixed_height), PIL.Image.NEAREST)
image.save(export_path+collection+str(index)+'.webp', 'webp', optimize=True, quality=90)
resize()
Hints
For this project, I chose the .webp format. Choose the configuration according to your requirements. Create exported image files before running the code.
Overall, it is always recommended to compress and resize your images to have a smaller file size. As images correlate with search engine optimization, it is relevant to compress and resize them as per your needs.