def limit_to_max_size(img, max_size):
    """
    Limit the image size to max size and scale the image,
    if max size exceeded.
    `img`: The image to validate as Pillow Image.
    `max_size`: The max allowed image size.
    :return: The eventually resized image.
    """
    biggest_size = max(img.size)
    if max_size and biggest_size > max_size:
        ratio = 1.0 * max_size / biggest_size
        img = img.resize([int(ratio * s) for s in img.size])
    return img