import os
import fnmatch
from pathlib import Path
from PIL import Image

# SETTINGS ###################################################################################
# maximum width of image
max_width = 1024
# maximum height of image
max_height = 720
##############################################################################################
# path of images folder
path_images = Path(r"")
##############################################################################################
# path of new images folder
path_images_new = Path(r"")
##############################################################################################


# get all files of defined type from folder
def listdir(dir_name, pattern="*"):
    return fnmatch.filter(os.listdir(dir_name), pattern)


# find all labels, images and parameters in path folder
images_array = listdir(str(path_images), "*.jpg")

print(len(images_array))
for i in range(len(images_array)):
    pic_full_path = (str(path_images) + '\\' + str(images_array[i]))
    pic_full_new_path = (str(path_images_new) + '\\' + str(images_array[i]))
    pic = Image.open(pic_full_path)
    pic = pic.convert('RGB')
    # resizing ###############################################################################
    width_per = (max_width / float(pic.size[0]))
    height_per = (max_height / float(pic.size[1]))
    if (width_per >= 1) and (height_per >= 1):
        pic.save(pic_full_new_path)
        print("resizing not performed")
        print(str(pic.size[0]) + "x" + str(pic.size[1]))
        continue
    if width_per <= height_per:
        height_new_size = int((float(pic.size[1]) * float(width_per)))
        pic = pic.resize((max_width, min(max_height, height_new_size)), Image.ANTIALIAS)
    else:
        width_new_size = int((float(pic.size[0]) * float(height_per)))
        pic = pic.resize((min(max_width, width_new_size), max_height), Image.ANTIALIAS)
    print("resized")
    print(str(pic.size[0]) + "x" + str(pic.size[1]))
    pic.save(pic_full_new_path)

    ##########################################################################################



