Skip to content

Instantly share code, notes, and snippets.

@sturmenta
Created October 11, 2022 07:31
Show Gist options
  • Save sturmenta/9ea94ad3f581d0b00fab1cd14b083fb6 to your computer and use it in GitHub Desktop.
Save sturmenta/9ea94ad3f581d0b00fab1cd14b083fb6 to your computer and use it in GitHub Desktop.
resize image and keep aspect ratio
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