Skip to content

Instantly share code, notes, and snippets.

@tysheng
Forked from rayrinaldy/compress.py
Created March 14, 2023 02:34
Show Gist options
  • Save tysheng/d8944d8e50d7c74838fd51b3df8b2331 to your computer and use it in GitHub Desktop.
Save tysheng/d8944d8e50d7c74838fd51b3df8b2331 to your computer and use it in GitHub Desktop.
Image Compression with Python
#!/usr/bin/env python
# Author: Ray Rinaldy
# pip install Pillow
# put this script in every image folder that wants to be converted
# run python compress.py
#
# This script will works on .jpg, .jpeg & .png (for png files, it will auto convert to have white background)
import os, glob, PIL, sys
from PIL import Image
size = 800, 800
script_dir = os.path.dirname(os.path.abspath(__file__))
dest_dir = os.path.join(script_dir, 'compressed')
fill_color = '#ffffff'
try:
os.makedirs(dest_dir)
except OSError:
pass # already exists
for infile in os.listdir(script_dir):
if os.path.splitext(infile)[1].lower() in ('.jpg', '.jpeg', '.png'):
file, ext = os.path.splitext(infile)
image = Image.open(infile)
if image.mode in ('RGBA', 'LA'):
background = Image.new(image.mode[:-1], image.size, fill_color)
background.paste(image, image.split()[-1])
image = background
image.thumbnail(size)
image.save(dest_dir + '/' + file + ".jpg", "JPEG", optimize=True, quality=85)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment