Created
July 3, 2023 01:23
-
-
Save swharden/f2b84d2d86f6e3a069c546f13aed6b62 to your computer and use it in GitHub Desktop.
Resize every image in a folder to create small and medium versions
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 every image in a folder to create small and medium versions. | |
""" | |
import pathlib | |
from PIL import Image | |
def resize_width(path: pathlib.Path, out_folder: str, new_width: int): | |
"""Resize a image to use the given width.""" | |
out_folder = pathlib.Path(out_folder) | |
out_folder.mkdir(exist_ok=True) | |
out_file = out_folder.joinpath(path.name) | |
im = Image.open(path) | |
width, height = im.size | |
new_height = int(new_width / width * height) | |
new_size = (new_width, new_height) | |
im2 = im.resize(new_size) | |
im2.save(out_file) | |
print(f"Saved {new_size}: {out_file}") | |
def resize_height(path: pathlib.Path, out_folder: str, new_height: int): | |
"""Resize a image to use the given height.""" | |
out_folder = pathlib.Path(out_folder) | |
out_folder.mkdir(exist_ok=True) | |
out_file = out_folder.joinpath(path.name) | |
im = Image.open(path) | |
width, height = im.size | |
new_width = int(new_height / height * width) | |
new_size = (new_width, new_height) | |
im2 = im.resize(new_size) | |
im2.save(out_file) | |
print(f"Saved {new_size}: {out_file}") | |
if __name__ == '__main__': | |
source_folder = "./full/" # contains original sized images | |
for file in pathlib.Path(source_folder).glob("*.jpg"): | |
resize_width(file, "./mid", 800) | |
resize_height(file, "./thumb", 200) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment