mirror of
https://github.com/FAUSheppy/homelab_gamevault
synced 2025-12-06 06:51:36 +01:00
feat: automatic image croping to match aspect ratio
This commit is contained in:
@@ -1,11 +1,20 @@
|
||||
import PIL
|
||||
|
||||
def load_and_keep_aspect_rescale(path, target_x, target_y):
|
||||
'''Load an image and resize it while keeping the aspect ratio (crop if it doesnt fit)'''
|
||||
def smart_resize(img, height, width):
|
||||
'''Crop to aspect ratio and then resize'''
|
||||
|
||||
img = PIL.Image.open(path)
|
||||
# get size
|
||||
# img.size()
|
||||
current_height, current_width = img.size
|
||||
target_ratio = height/width
|
||||
current_ratio = current_height/current_width
|
||||
|
||||
img = img.resize((x-2*30, y-2*30))
|
||||
img = PIL.ImageTk.PhotoImage(img)
|
||||
if current_ratio > target_ratio:
|
||||
target_crop_height = current_width*target_ratio
|
||||
diff = current_height - target_crop_height
|
||||
img = img.crop((diff/2, 0, current_height-diff/2, current_width))
|
||||
elif current_ratio < target_ratio:
|
||||
target_crop_width = current_height/target_ratio
|
||||
diff = current_width - target_crop_width
|
||||
img = img.crop((0, diff/2, current_height, current_width-diff/2))
|
||||
|
||||
img = img.resize((height, width))
|
||||
return img
|
||||
Reference in New Issue
Block a user