Skip to content

Instantly share code, notes, and snippets.

@kols
Created December 11, 2012 04:20
Show Gist options
  • Save kols/4255843 to your computer and use it in GitHub Desktop.
Save kols/4255843 to your computer and use it in GitHub Desktop.
Compress and upload image using PIL and fabric
import argparse
import os
import sys
from PIL import Image
OUTPUT_DIR = 'output'
OUTPUT_SIZE = (3000, 1500)
class Compress(object):
def __init__(self):
self.input_dir = None
self.output_dir = OUTPUT_DIR
self.output_size = OUTPUT_SIZE
self.processed_dirs = set()
def set_input_dir(self, input_dir):
self.input_dir = input_dir
def _compress(self, input, output, size=OUTPUT_SIZE):
image = Image.open(input)
output_dir = os.path.dirname(output)
if not os.path.isdir(output_dir):
os.makedirs(output_dir, 0755)
image = image.resize(size, Image.ANTIALIAS)
print 'Compressing: %s -> %s' % (input, output)
image.save(output, quality=90)
def collect_image(self):
for path, dirs, files in os.walk(self.input_dir):
try:
dirs.remove(self.output_dir)
except Exception:
pass
for f in files:
input = os.path.join(path, f)
output = os.path.join(path, self.output_dir, f)
yield input, output, self.output_size
def compress(self):
for image_info in self.collect_image():
try:
self._compress(*image_info)
except Exception as X:
print >>sys.stderr, "%s: %s" % (X, image_info[0])
else:
input_dir = os.path.dirname(image_info[0])
output_dir = os.path.dirname(image_info[1])
self.processed_dirs.add((input_dir, output_dir))
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('dirs', metavar='DIR', type=str, nargs='+',
help='Dir containing the images to be compressed')
args = parser.parse_args()
compress = Compress()
for dir in args.dirs:
compress.set_input_dir(dir)
compress.compress()
import os.path
import pipes
from fabric.api import env, task
from compress import Compress
from fabric.contrib.project import rsync_project
env.remote_image_dir = '/home/media/images/apps/demopanorama'
env.hosts = ['srv0v1:10022']
env.user = 'deploy'
@task
def compress_image(*dirs):
compress = Compress()
for dir in dirs:
compress.set_input_dir(dir)
compress.compress()
return compress
@task
def upload_image(dirname, local_dir):
if not local_dir.endswith('/'):
local_dir += '/'
local_dir = pipes.quote(local_dir)
remote_dir = pipes.quote(os.path.join(env.remote_image_dir, dirname)
).replace(' ', '\ ')
rsync_project(remote_dir=remote_dir, local_dir=local_dir)
@task
def compress_and_upload(*dirs):
compress = compress_image(*dirs)
for input_dir, output_dir in compress.processed_dirs:
dirname = os.path.basename(input_dir)
upload_image(dirname, output_dir)
argparse==1.2.1
Fabric==1.5.1
Pillow==1.7.8
paramiko==1.9.0
pycrypto==2.6
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment