Compress an image to minimize memory size in Python
According to various surveys conducted it is seen that around 60-65% of the internet traffic consists of the images. The media-rich websites see to it that their images are optimized to speed up their website. A website with fast loading and enough images makes the user’s happy. Thus there is a much need to compress an image to minimize the memory size for easy uploading.
How to Compress an image to reduce file size in Python
Now here comes the question of how to minimize the memory size of the images.
There are various libraries in python available for image manipulation and optimization the one we will be using today is tinify. This tinify supports various file formats like PNG and JPG.
Please follow the following instructions for the tinify installation.
pip install --upgrade tinify
this command will upgrade your tinify if already installed or if not installed will do it automatically from scratch. This will install all the required libraries for the same in your Python.
The steps to compress an image to minimize memory size in Python3 are as follows:
- Import the tinify module.
- Now use the tinify.from_file(‘<your_file_location_in_png/jpg_format only>’).to_file(‘<name_of output_file>’)
- Before this you have to obtain your API key from tinify.
- Obtain tinify API from the tinijpg.com by registering your email.
- How To Convert Image To Matrix Using Python
- Detect number of faces from an image in Python using OpenCV
Now let’s begin with the code in Python.
Program in Python (Compress an image to minimize memory size)
import tinify tinify.key = '<your API key>' tinify.from_file('/root/Desktop/amber.jpg').to_file('optimized.jpg')
(Note: make sure that the output and input extensions match)
Execute, the code. The execution may take some time to say about a minute or two depending upon the internet speed.
There are various other modules that help in image manipulation and optimizing some of them are scikit-image, pillow, img4web and many more. They also provide support for converting image formate from one to another and resizing the image and various other things. For more read the documentation for the same.
Thank You till next time Happy coding!!