Skip to content

Instantly share code, notes, and snippets.

@NicholasBallard
Last active August 16, 2020 04:28
Show Gist options
  • Save NicholasBallard/131e2bec7aa80615e33a3268bb01285e to your computer and use it in GitHub Desktop.
Save NicholasBallard/131e2bec7aa80615e33a3268bb01285e to your computer and use it in GitHub Desktop.
""" 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()
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