TinyPNG uses smart lossy compression techniques to reduce the file size of your WEBP, JPEG and PNG files. By selectively decreasing the number of colors in the image, fewer bytes are required to store the data. The effect is nearly invisible but it makes a very large difference in file size!
TinyPNG has web app that allows us to compress images(up to 20 images & max 5MB each). That is useful but we sometimes need to compress more than 20 images.
The great thing is that TinyPNG has API and packages for multiple languages.
The script is super simple. create a src for source images and dist for optimized images.
Get file names by glob and pass image files to TinyPng API with tinify.from_file method.
You can pass an image file as buffer or image url instead of an image file path.
importtinifyfromglobimportglobimportos.pathtinify.key="your_api_key"source_dir_name='src'destination_dir_name='dist'# get all files names in directory
files=glob(source_dir_name+'/*')# compress all files
forfileinfiles:print('compressing '+file)source=tinify.from_file(file)file_name,ext=os.path.splitext(file)file_name=file_name.replace(source_dir_name+'/','')source.to_file(destination_dir_name+"/"+file_name+".png")print('compressed all images')
Step4. Run the script
Before running the script, we need 2 small things.
First, create two directories(src and dist). If you don't like these dir names, you can change whatever you like.
$ mkdir src dist
Then, moving image files you want to compress to src dir.