Skip to content

Instantly share code, notes, and snippets.

@genzj
Created July 22, 2019 05:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save genzj/504d239225b6faa0fce9eee628241510 to your computer and use it in GitHub Desktop.
Save genzj/504d239225b6faa0fce9eee628241510 to your computer and use it in GitHub Desktop.
crop and resize images, powered by PIL
# -*- encoding: utf-8 -*-
import logging
import os.path
import sys
from PIL import Image
logging.basicConfig(level=logging.INFO)
L = logging.getLogger(__name__)
L.setLevel(logging.INFO)
def resize_image(image, scale=(0.5, 0.5)):
new_size = tuple(x * scale[idx] for idx, x in enumerate(image.size))
L.info(
'resize %s %spx x %spx to %spx x %spx',
image, image.size[0], image.size[1],
new_size[0], new_size[1]
)
image.thumbnail(new_size)
def crop_image(image, scale=(0.5, 0.5), origin=(0.0, 0.0)):
box = (origin[0], origin[1], scale[0] * image.size[0] + origin[0], scale[1] * image.size[1] + origin[1])
L.info(
'crop %s %spx x %spx to %s',
image, image.size[0], image.size[1],
box
)
return image.crop(box)
def main():
for src in sys.argv[1:]:
with Image.open(src) as image:
dest = '%s_changed%s' % os.path.splitext(src)
image = crop_image(image, scale=(0.82, 0.45))
resize_image(image, scale=(0.8, 0.8))
image.save(dest)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment