How to Optimize Images With Python
Have you ever wondered to optimize images on your website? Do you want to make an easy-to-load website? If you said yes, then this is the right place to be.
Join the DZone community and get the full member experience.
Join For FreeRecently, I have found the perfect solution to optimize images in no time without any tools, plugins, or software.
All you need is a few Python Scripts and images that you want to optimize.
I am not a web developer, so don't worry, this is not going to be difficult!
But, before I begin, I want to share why it is necessary to optimize images.
Reasons to Optimize Images
- Adds visuals: This helps to gain 2.3X more engagement than not having images. But, when you add images on your server (website), it increases load time, which ultimately affects your ranking. Hence, it is mandatory for one to optimize images.
- Helps To Get More Traffic: Having images on your website or blog helps you to get more traffic from Google/Bing images.
I think these two reasons are enough for you. Now, let's focus on how to optimize images without any effort.
How to Optimize Images With Python Scripts
1. Install Python
First, we will have to install Python. I am using windows, so I am downloading it for Windows.
Next, install it, but keep in mind that you have to click on "Add Python 3.9 (Your Version) To Path" and, then, select "Customize Installation".
Step 3 is to check all the "Optional Functions".
Now, press the "Next" button and, then, the "Install" button.
For step five, after installation, click on "Disable path length limit".
Finally, we have installed and set up Python.
2. Optimize Images
We are ready to optimize our images. Also, take a backup of your images because once you optimize them, you have no option to retrieve the old versions.
First, press "Start" in your windows and search "CMD". Press the right button of the mouse and select "Run as administrator".
Then, you will get a screen like mine.
Now, type "pip3 install pillow optimize-images", and press enter.
If you get such a warning then type "python -m pip install --upgrade pip" and press enter. Otherwise, you can skip the 5th and 6th points.
In the next line, type "pip3 install pillow optimize-images" again and press enter.
Now, select the path of the image folder where you have collected all of them. It is "D:\How To Optimize Images" in my case.
Next, type "pushd [space] {folder url}" and press enter. In my case, I have typed "PushD D:\How To Optimize Images".
Now, check the size of the image folder first so you can see the difference. "21.8 MB" is mine.
Now, on CMD dashboard, type "optimize-images [space] ./".
And, Press enter.
You are done. Now, check the size of the image folder.
After optimizing your images, you can use them on your website without increasing loading time.
Opinions expressed by DZone contributors are their own.
Comments