Created
October 30, 2018 02:49
-
-
Save rayrinaldy/20b645574a45c18f47c83b64fb3915eb to your computer and use it in GitHub Desktop.
Image Compression with 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
#!/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