Files
developer-toolbox/image-converter/src/modules/image_parser.py

44 lines
1.6 KiB
Python

from PIL import Image
import os
import math
def parse_image(src: str, target_src: str, max_vertical_size_px: int, max_horizontal_size_px: int, target_extension: str):
if (src == None):
return
if (target_extension == None):
target_extension = "png"
rawImage = Image.open(src)
if (rawImage.height > rawImage.width):
if (max_vertical_size_px == None or max_vertical_size_px < 1):
max_vertical_size_px = rawImage.height
target_height = max_vertical_size_px
target_width = math.ceil(rawImage.width * max_vertical_size_px / rawImage.height)
else:
if (max_horizontal_size_px == None or max_horizontal_size_px < 1):
max_horizontal_size_px = rawImage.width
target_width = max_horizontal_size_px
target_height = math.ceil(rawImage.height * max_horizontal_size_px / rawImage.width)
rawImage = rawImage.resize((target_width, target_height))
filename = os.path.basename(src)
last_dot = filename.rfind(".")
filename = filename[:last_dot] + "." + target_extension
if (target_src == None):
target_src = os.path.abspath(os.path.dirname(src))
else:
target_src = os.path.abspath(target_src)
full_path = os.path.join(target_src, filename)
rawImage.save(full_path)
def parse_whole_directory(dir_src: str, target_src: str, max_vertical_size_px: int, max_horizontal_size_px: int, target_extension: str):
for file_path in get_file_path_iter(dir_src):
parse_image(file_path,target_src, max_vertical_size_px, max_horizontal_size_px, target_extension)
def get_file_path_iter(directory):
for dirpath,_,filenames in os.walk(directory):
for f in filenames:
yield os.path.abspath(os.path.join(dirpath, f))