Created
May 31, 2021 21:29
-
-
Save ivansaul/8814ef418a693db17dd4e22db69d7d53 to your computer and use it in GitHub Desktop.
Python: How to reduce the image file size with python| How to compress images in python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#https://tinypng.com/developers | |
#Free first 500 images per month | |
#pip install tinify | |
import tinify | |
tinify.key = "YOUR_API_KEY" | |
#Compressing images | |
source = tinify.from_file("unoptimized.jpg") | |
source.to_file("optimized.jpg") | |
#Resizing images | |
source = tinify.from_file("large.jpg") | |
resized = source.resize( | |
method="fit", | |
width=150, | |
height=100 | |
) | |
resized.to_file("thumbnail.jpg") | |
#Compressing and Resizing multiple images | |
def tiny_png(src): | |
source = tinify.from_file(src) | |
resized = source.resize( | |
method="scale", | |
width=300) | |
resized.to_file(src) | |
directory = "images" | |
for root, subdirectories, files in os.walk(directory): | |
for file in files: | |
src=os.path.join(root, file) | |
if src.endswith(('png','jpg')): | |
tiny_png(src) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment