Last active
November 23, 2022 10:24
-
-
Save erfanhs/95c1210e3604de67f2abb42b13bf24cc to your computer and use it in GitHub Desktop.
Get new dimensions by changing width or height ( remain aspect ratio )
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def gcd(x, y): # Simplify Fraction (Greatest common divisor) | |
if (x < y): | |
temp = x | |
x = y | |
y = temp | |
while (y != 0): | |
remainder = x % y | |
x = y | |
y = remainder | |
r = x | |
return r | |
def get_ratio(w, h): # Get Aspect Ratio Based on Width and Height | |
res = gcd(w, h) | |
a1 = int(w / res) | |
a2 = int(h / res) | |
return a1, a2 | |
def resize(old_width, old_height, new_quality=1080): | |
sum_size = old_width + old_height | |
w_ratio, h_ratio = get_ratio(old_width, old_height) | |
sum_ratio = w_ratio + h_ratio | |
factor = sum_size / sum_ratio | |
if old_width > old_height: | |
new_width = new_quality | |
new_height = h_ratio * (new_width / w_ratio) | |
elif old_width < old_height: | |
new_height = new_quality | |
new_width = w_ratio * (new_height / h_ratio) | |
else: | |
new_width = new_height = new_quality | |
return int(new_width), int(new_height) | |
""" | |
use for Pillow: | |
from PIL import Image | |
im = Image.new("image.jpg") | |
old_width, old_height = im.size | |
new_width, new_height = resize(old_width, old_height, 1920) | |
im = im.resize((new_width, new_height)) | |
im.save("image-resized.jpg") | |
""" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment