Skip to content

Instantly share code, notes, and snippets.

@danielthiel
Last active August 29, 2015 13:56
Show Gist options
  • Save danielthiel/9295089 to your computer and use it in GitHub Desktop.
Save danielthiel/9295089 to your computer and use it in GitHub Desktop.
Scale a picture/image in python with PIL (pil-python)
""" some documentation:http://www.effbot.org/imagingbook/ """
from PIL import ImageOps
from PIL import Image
def scale_picture(img_path, size=(150,150), save_path='/tmp', subdir=False):
"""
img_path: absolute path to a picture
size: (width, height) tuple
save_path: where the new files be saved
subdir: if True, the scaled image will be saved within a directory located in save_path named after the resolution
"""
# get current filename:
img_name = os.path.basename(img_path)
if subdir:
# create a savedir with name by new size:
save_dir = u'{0}x{1}'.format(size[0], size[1])
# create subdir in save_path if not exiting:
if not os.path.isdir(save_dir):
os.makedirs(save_dir)
else:
# save new file without any sub directory:
save_dir = ''
# the new absolute path of the to be created picture:
save_path = os.path.join(save_path, save_dir, img_name)
# open image, edit to new size and save it
img = Image.open(img_path)
img = ImageOps.fit(img, size, Image.ANTIALIAS)
""" img.save(outfile, format, options…)
format defines options
e.g. 'JPEG' options: quality=80, optimize=True, progressive=True
"""
img.save(save_path, 'JPEG')
return save_path
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment