Created
October 11, 2022 07:31
-
-
Save sturmenta/9ea94ad3f581d0b00fab1cd14b083fb6 to your computer and use it in GitHub Desktop.
resize image and keep 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
type OneRequiredOneOptional = | |
| {desiredWidth: number; desiredHeight?: number} | |
| {desiredWidth?: number; desiredHeight: number}; | |
interface CommonProps { | |
widthReadFromImage: number; | |
heightReadFromImage: number; | |
} | |
type FullProps = CommonProps & OneRequiredOneOptional; | |
export const getNewImageSizeByAspectRatio = ({ | |
widthReadFromImage, | |
heightReadFromImage, | |
desiredWidth, | |
desiredHeight, | |
}: FullProps) => { | |
let ratio = 1; | |
if (desiredWidth && desiredHeight) { | |
ratio = Math.min( | |
desiredWidth / widthReadFromImage, | |
desiredHeight / heightReadFromImage, | |
); | |
} else if (desiredWidth) { | |
ratio = desiredWidth / widthReadFromImage; | |
} else if (desiredHeight) { | |
ratio = desiredHeight / heightReadFromImage; | |
} | |
return { | |
finalWidth: widthReadFromImage * ratio, | |
finalHeight: heightReadFromImage * ratio, | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment