Created
July 31, 2021 04:36
-
-
Save jasonacox/c64a0ef6dc65114372d96a91d64ecc5e to your computer and use it in GitHub Desktop.
Python script to resize all images in a directory
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
# Resize Images in Directory | |
# | |
# Provided target frame size (TARGETX, TARGETY) this script will scan current | |
# directory and scale up an image (keeping same ratio) to best fit. I used | |
# this to fix images for a photo frame that would only scale down images but | |
# would not scale up. | |
# | |
# Jason A Cox - github.com/jasonacox | |
# 2021 July 30 | |
# | |
from PIL import Image | |
import os | |
# Set the target limits for resize | |
TARGETX = 1080 | |
TARGETY = 1920 | |
# List files in current directory | |
entries = filter(os.path.isfile, os.listdir( os.curdir )) | |
for entry in entries: | |
tx = 0 | |
ty = 0 | |
if(entry.startswith(".")): | |
continue | |
im = Image.open(entry) | |
(x,y) = im.size | |
ratio = y/x | |
#print("> ratio = %f" % ratio) | |
if( y < TARGETY and x < TARGETX): | |
# need to adjust size | |
if(ratio > 1.0): | |
# Tall picture - use y for scale | |
scale = TARGETY/y | |
else: | |
scale = TARGETX/x | |
#print("> scale = %f" % scale) | |
tx = x * scale | |
ty = y * scale | |
newsize = (int(tx), int(ty)) | |
print("> Processing %s - scaling up from %dx%d to %dx%d" % (entry, x, y, tx, ty)) | |
# resize | |
im2 = im.resize(newsize) | |
im2.save(entry) | |
else: | |
# already right size | |
print("> Processing %s - no change %dx%d" % (entry, x, y)) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment