Skip to content

Instantly share code, notes, and snippets.

@ivansaul
Created May 31, 2021 21:29
Show Gist options
  • Save ivansaul/8814ef418a693db17dd4e22db69d7d53 to your computer and use it in GitHub Desktop.
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
#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