Skip to content

Instantly share code, notes, and snippets.

@insaneyilin
Created July 1, 2019 17:41
Show Gist options
  • Save insaneyilin/d7919b9467c1aa28fccaef9e9f07fda3 to your computer and use it in GitHub Desktop.
Save insaneyilin/d7919b9467c1aa28fccaef9e9f07fda3 to your computer and use it in GitHub Desktop.
compress image with file size threshold
# -*- coding: utf-8 -*-
# @Author: insaneyilin
# Python version 2.7
# Reference: https://www.cnblogs.com/li1992/p/10675769.html
import os
import sys
import argparse
import glob
from PIL import Image
def get_args():
arg_parser = argparse.ArgumentParser()
arg_parser.add_argument('src_dir', type=str, help='source directory')
arg_parser.add_argument('dest_dir', type=str, help='destination directory')
arg_parser.add_argument('--thresh', type=float, help='image size threshold in MB',
default=1.0)
return arg_parser.parse_args()
def get_out_filename(in_file, dest_dir):
dir_path, filename = os.path.split(in_file)
# fname, ext = os.path.splitext(filename)
return os.path.join(dest_dir, filename)
def compress_image(in_file, out_file, size_thresh, step=10, quality=80):
in_file_size = os.path.getsize(in_file)
if in_file <= size_thresh:
return in_file
compressed_file_size = in_file_size
while compressed_file_size > size_thresh:
im = Image.open(in_file)
im.save(out_file, quality=quality)
if quality - step <= 0:
break
quality -= step
compressed_file_size = os.path.getsize(out_file)
return compressed_file_size
if __name__ == '__main__':
args = get_args()
print "source dir: {}".format(args.src_dir)
print "destination dir: {}".format(args.dest_dir)
print "image size threshold: {}".format(args.thresh)
thresh_in_bytes = args.thresh * 1024.0 * 1024.0
filenames = glob.glob('{}/*'.format(args.src_dir))
for filename in filenames:
with Image.open(filename) as img:
img_filesize = os.path.getsize(filename)
print "\n{} {} MB".format(filename, img_filesize/(1024.0**2))
out_filename = get_out_filename(filename, args.dest_dir)
if not os.path.exists(args.dest_dir):
os.mkdir(args.dest_dir)
out_file_size = compress_image(filename, out_filename, thresh_in_bytes)
print "after compression: {} {} MB".format(out_filename, out_file_size/(1024.0**2))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment