Welcome folks today in this blog post we will be bulk
compressing multiple png
and jpeg
images present in the same directory or specific directory in python using pillow
library. All the source code of the application is given below.
Get Started
In order to get started you need to install the following library inside your python project using the pip
command as shown below
pip install pillow
After installing this library you need to make an app.py
file and copy paste the following code
app.py
from PIL import Image
import os
def compress_images(directory=False, quality=30):
# 1. If there is a directory then change into it, else perform the next operations inside of the
# current working directory:
if directory:
os.chdir(directory)
# 2. Extract all of the .png and .jpeg files:
files = os.listdir()
# 3. Extract all of the images:
images = [file for file in files if file.endswith(('jpg', 'png'))]
# 4. Loop over every image:
for image in images:
print(image)
# 5. Open every image:
img = Image.open(image)
# 5. Compress every image and save it with a new name:
img.save("Compressed_and_resized_with_function_"+image, optimize=True, quality=quality)
compress_images()
So in the above python script as you can see we are importing the pillow
library and also the os
module which is a built in module in python which is used to get the current working directory and also address of specific
directory
And now if you execute this python
script by running the below command
python app.py
As you can see in my function call
i didn’t provided the directory parameter so the directory parameter is false in this case the python script has taken the current working directory
according to the logic of the script so all the images that are present inside the root directory of the project is automatically compressed to smaller or reduced size and you can see in the above screenshot all the output compressed
images are created
And now if we provide the directory explicitly
in which all the input images are present. Let’s suppose we create a directory called as uploads
and then uploads all the images to it as shown below
So now we need to provide the address of the directory at the time of calling the function so we need to modify
the python script a little bit as shown below
app.py
from PIL import Image
import os
def compress_images(directory=False, quality=30):
# 1. If there is a directory then change into it, else perform the next operations inside of the
# current working directory:
if directory:
os.chdir(directory)
# 2. Extract all of the .png and .jpeg files:
files = os.listdir()
# 3. Extract all of the images:
images = [file for file in files if file.endswith(('jpg', 'png'))]
# 4. Loop over every image:
for image in images:
print(image)
# 5. Open every image:
img = Image.open(image)
# 5. Compress every image and save it with a new name:
img.save("Compressed_and_resized_with_function_"+image, optimize=True, quality=quality)
compress_images("uploads")