Last active
August 16, 2020 04:28
-
-
Save NicholasBallard/131e2bec7aa80615e33a3268bb01285e to your computer and use it in GitHub Desktop.
This file contains 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
""" resize.py | |
""" | |
from __future__ import annotations | |
import os | |
import glob | |
from pathlib import Path | |
import sys | |
import click | |
from PIL import Image | |
""" | |
Pillow supports lots more: | |
https://pillow.readthedocs.io/en/5.1.x/handbook/image-file-formats.html | |
""" | |
SUPPORTED_FILE_TYPES: list[str] = [".jpg", ".png"] | |
def name_file(fp: Path, suffix) -> str: | |
return f"{fp.stem}{suffix}{fp.suffix}" | |
def resize(fp: str, scale: Union[float, int]) -> Image: | |
""" Resize an image maintaining its proportions | |
Args: | |
fp (str): Path argument to image file | |
scale (Union[float, int]): Percent as whole number of original image. eg. 53 | |
Returns: | |
image (np.ndarray): Scaled image | |
""" | |
_scale = lambda dim, s: int(dim * s / 100) | |
im: PIL.Image.Image = Image.open(fp) | |
width, height = im.size | |
new_width: int = _scale(width, scale) | |
new_height: int = _scale(height, scale) | |
new_dim: tuple = (new_width, new_height) | |
return im.resize(new_dim) | |
@click.command() | |
@click.option("-p", "--pattern") | |
@click.option("-s", "--scale", default=50, help="Percent as whole number to scale. eg. 40") | |
@click.option("-q", "--quiet", default=False, type=bool, help="Suppresses stdout.") | |
def main(pattern: str, scale: int, quiet: bool): | |
for image in (images := Path().glob(pattern)): | |
if image.suffix not in SUPPORTED_FILE_TYPES: | |
continue | |
im = resize(image, scale) | |
nw, nh = im.size | |
suffix: str = f"_{scale}_{nw}x{nh}" | |
resize_name: str = name_file(image, suffix) | |
_dir: Path = image.absolute().parent | |
im.save(_dir / resize_name) | |
if not quiet: | |
print( | |
f"resized image saved to {resize_name}.") | |
if images == []: | |
print(f"No images found at search pattern '{pattern}'.") | |
return | |
if __name__ == '__main__': | |
main() |
This file contains 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
from setuptools import setup | |
setup( | |
name='resize', | |
version='0.0.1', | |
py_modules=['resize'], | |
install_requires=[ | |
'click', | |
'pillow', | |
], | |
entry_points=''' | |
[console_scripts] | |
resize=resize:main | |
''' | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment