For my current web project I need to upload 200 images to my website. All of them are in the same folder. Here’s the problem:
π€― Challenge: My images have file sizes of 2 to 3 MB, so they are far too big and will significantly slow down my website.
π To reduce the file sizes of those images before uploading them to my website, I wrote a simple Python script that goes over each image in a folder and compresses them to 1200 pixels width (for example).
I share this script because you may want to do the same. If so, you can simply place this script above the folder where you have stored all images to be compressed. Ensure there’s an output
folder because the compressed images will be placed there.
In particular, here’s an example folder structure, folders in bold
:
some_folder
-- compress.py (this Python script)
-- my_foldername
---- image1.jpg
---- image2.png
---- image3.jpg
-- output
Now copy&paste the following Python code into a new file compress.py
and store it in your outer folder some_folder
:
File compress.py
:
from PIL import Image import os # Your Folder Name Here: foldername = './my_foldername' # Your Desired Width Here (in Pixels): max_width = 1200 # pixels # Get a list of all the image files in the folder images = [f for f in os.listdir(foldername)] print(images) for img in images: # Load the image image = Image.open(foldername + img) # Calculate the aspect ratio width, height = image.size aspect_ratio = width / height # Calculate the new height new_height = max_width / aspect_ratio # Resize the image image = image.resize((max_width,round(new_height))) # Save the image filename = './output/' + img image.save(filename, optimize=True, quality=85)
The script automatically computes the height, given the maximal width.
If you run this Python script, you’ll see that it compresses all files in the input folder.
Here are the input file sizes:
And here are the output file sizes:
Much smaller! Many of them have reduced file sizes by more than 700%! And they still look good!
Here’s an example before/after image after running the conversion script:
Before:
After:
I bet you can barely see any difference! π
If you want to learn and improve your Python skills, feel free to check out our email academy and our premium Finxter Computer Science Academy with plenty of advanced coding courses!