Skip to content

Instantly share code, notes, and snippets.

@addohm
Created October 2, 2022 01:08
Show Gist options
  • Save addohm/638f430d3e2b9112a8e5b4cf5d26e053 to your computer and use it in GitHub Desktop.
Save addohm/638f430d3e2b9112a8e5b4cf5d26e053 to your computer and use it in GitHub Desktop.
Convert images to thumbnails in their own directory
import os
import platform
from PIL import Image
'''
Run from parent directory. Folders and files expected in `./files/images`
'''
opsys = platform.system()
if opsys.lower() == 'windows':
SLASH = "\\"
else:
SLASH = "/"
last_str = ''
def state_update(str):
global last_str
if str != last_str:
print(str)
last_str = str
def thumbnailify(path, file):
'''
Converts the input image (path) to a thumbnail at the thumbnail path prefixed with `thumb_`
'''
global SLASH
fullpath = path + SLASH + file
thumbnail_path = f"{path}{SLASH}thumbnails"
try:
image = Image.open(fullpath)
# Convert the image to a thumbnail
image.thumbnail((200,200))
# Check to make sure the thumbnail container exists else create it
if not os.path.isdir(thumbnail_path):
os.makedirs(thumbnail_path)
print(f"Created directory: {thumbnail_path}")
# Assemble full thumbnail file path
thumbnail_file = f"{thumbnail_path}{SLASH}thumb_{file}"
# Delete the old thumbnail if it exists
if os.path.exists(thumbnail_file):
os.remove(thumbnail_file)
print(f"Removed old file: {thumbnail_file}")
# Save the thumbnail
image.save(thumbnail_file)
print(f"thumb_{file} created.")
except IOError:
pass
def main():
global SLASH
# Current PATH to images is where this file is located + \images
path = os.getcwd() + f"{SLASH}files{SLASH}images"
state_update(f"Expected image path: {path}")
# Initialize the directory list
directory_list = []
# Scan the directory and get
# an iterator of os.DirEntry objects
# corresponding to entries in it
# using os.scandir() method
base_path_obj = os.scandir(path)
# Build a list of directory paths
for obj in base_path_obj:
if obj.is_dir():
directory_list.append(obj.path)
# Convert each file in the directory list to a thumbnail if the file is a proper image
for directory in directory_list:
obj = os.scandir(directory)
for file in obj:
if file.is_file():
fullpath = directory + SLASH + file.name
img = Image.open(fullpath)
if img.format:
state_update(f"Creating thumbnails for {str(directory).split(SLASH)[-1]}".upper())
thumbnailify(directory, file.name)
else:
print(f"Rejecting file: {fullpath} because it is not a proper image file")
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment