Skip to content

Instantly share code, notes, and snippets.

@rayrinaldy
Created October 30, 2018 02:49
Show Gist options
  • Save rayrinaldy/20b645574a45c18f47c83b64fb3915eb to your computer and use it in GitHub Desktop.
Save rayrinaldy/20b645574a45c18f47c83b64fb3915eb 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