Skip to content

Instantly share code, notes, and snippets.

@StanGenchev
Created June 21, 2020 16:44
Show Gist options
  • Save StanGenchev/4ab30bec88785866c5d4a8f3aa769227 to your computer and use it in GitHub Desktop.
Save StanGenchev/4ab30bec88785866c5d4a8f3aa769227 to your computer and use it in GitHub Desktop.
Calculate resolution while preserving the aspect ratio with 'fit' effect in python.
def get_scaled_resolution(
self,
old_width: int = None,
old_height: int = None,
new_width: int = None,
new_height: int = None,
):
"""Returns the closest new resolution while preserving the aspect ratio.
You can specify new width, height or both.
It will automatically calculate the resolution.
It can be used for both downscaling and upscaling.
It will return either the same resolution you specified or bigger.
"""
if old_width is None or old_height is None or old_width < 1 or old_height < 1:
raise ValueError("Old width and height must be int values bigger than 0")
elif new_width is None and new_height is None:
raise ValueError("You must specify width or height or both.")
elif (new_width is not None and new_width < 1) or (
new_height is not None and new_height < 1
):
raise ValueError("New width and height must be int values bigger than 0")
else:
if new_height is None:
height = int(old_height / (old_width / new_width))
width = int(old_width / (old_height / height))
else:
width = int(old_width / (old_height / new_height))
height = int(old_height / (old_width / width))
if width < 1 or height < 1:
raise ValueError(
"Calculated resolution is too low - {0}x{1}.".format(width, height)
)
elif new_width == -1 or new_width is None:
return width, new_height
elif new_height == -1 or new_height is None:
return new_width, height
elif width == new_width and height == new_height:
return new_width, new_height
elif width > new_width:
return width, new_height
else:
return new_width, height
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment