Reduce image size without harming the quality of the image using python.
- Tejas Achar
- Sep 3, 2020
- 1 min read

Lets say you have a folder of 1000 images which you want to upload to your own website.
Or it may be taking up too much space on your storage.
It takes forever to compress each image size and save it.
Python has a library called PIL, this library is basically used for image manipulation, image processing jobs or any image related tasks.
Step 1: Install PIL using
pip install PIL
Step 2 : Create a ".py" file and paste the below code in it.
#importing libraries
from PIL import Image
import os
#Looping through files in the current directory
for i in os.listdir(os.getcwd()):
print(i)
#Skipping the .py file
if i.endswith(".py"):
continue
else:
image = Image.open(i)
#current image size
x = image.size
#Reduced image size
xx = tuple(int(ti/2) for ti in x)
print(xx)
print(image.size)
#Apply resize
image = image.resize(xx,Image.ANTIALIAS)
image.save("Optimized"+i,optimize = True, quality = 20)
#Remove old file
os.remove(i)
Step 3 : Place this python file in the directory where all the images or photos are present.
NOTE : Make sure the directory has only image type files like png, jpeg or any other image format.
Step 4 : Run the python file
python filename.py
And you can see all the optimized images in a fraction of seconds.
All the file size will be less than 50% of your initial file size.
For explanation of the code please check the comment lines in the code
Peace out!
Comentários