from PIL import Image
from torchvision.transforms import functional as trf



# --------------------------------------------------------------------------------------------------------------------
def resize_largest_side(img: Image.Image, target_size):
  w, h = img.size
  if w > h:  # width is larger
    new_w = target_size
    new_h = int(h * target_size / w)
  else:  # height is larger or equal
    new_h = target_size
    new_w = int(w * target_size / h)
  return trf.resize(img, [new_h, new_w], interpolation=trf.InterpolationMode.BICUBIC)  # use functional resize
# --------------------------------------------------------------------------------------------------------------------
def pad_to_square(img, target_size, fill=0):
  w, h = img.size
  pad_left = (target_size - w) // 2
  pad_top = (target_size - h) // 2
  pad_right = target_size - w - pad_left
  pad_bottom = target_size - h - pad_top
  return trf.pad(img, [pad_left, pad_top, pad_right, pad_bottom], fill=fill)
# --------------------------------------------------------------------------------------------------------------------