Created
July 22, 2019 05:38
-
-
Save genzj/504d239225b6faa0fce9eee628241510 to your computer and use it in GitHub Desktop.
crop and resize images, powered by PIL
This file contains hidden or 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
# -*- 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