Skip to content

Instantly share code, notes, and snippets.

@thesaadarshad
Last active September 18, 2022 10:04
Show Gist options
  • Save thesaadarshad/1b3de1d70f2005ed892bdeee539f6387 to your computer and use it in GitHub Desktop.
Save thesaadarshad/1b3de1d70f2005ed892bdeee539f6387 to your computer and use it in GitHub Desktop.
pictures_downscale
from PIL import Image
import os
from pathlib import Path
import PIL
def convert(filepath,fixed_height=1200):
path = Path(filepath)
filename = filepath.split("/")[-1:][0]
newfilebasefolder = path.parent.absolute()
newfilename = str(newfilebasefolder)+"/"+filename
try:
image = Image.open(filepath)
height_percent = (fixed_height / float(image.size[1]))
width_size = int((float(image.size[0]) * float(height_percent)))
image = image.resize((width_size, fixed_height), PIL.Image.NEAREST)
print(f'Saving New File: {newfilename}')
image.save(newfilename)
except Exception as e:
print(f"failed: {e}")
def getListing(path):
path_contents = []
for directory_list in os.listdir(path):
if not directory_list.startswith('.'):
path_contents.append(directory_list)
return path_contents
def is_it_a_file(content):
if content.endswith(".png") or content.endswith(".JPG") or content.endswith(".jpg") or content.endswith(".JPEG") or content.endswith(
".jpeg" ):
return True
else:
return False
def iterateFolder(root_directory):
print(f'Digging into: {root_directory}')
directory_listing = getListing(root_directory)
print(f'Directory Contents: {directory_listing}')
for contents in directory_listing:
new_path = os.path.join(root_directory,contents)
print(f'Checking in: {contents}')
if is_it_a_file(contents):
print(f"'{contents}': its a valid file found at '{new_path}'")
convert(new_path)
print("--")
else:
print(f"'{contents}': its a directory. we go further in '{new_path}'")
try:
iterateFolder(new_path)
except:
print(f'Error getting into: {new_path}')
if __name__ == '__main__':
iterateFolder(os.getcwd())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment