Last active
November 15, 2022 13:15
-
-
Save danielhaim1/22658fb489d89660f63ef47407092738 to your computer and use it in GitHub Desktop.
Return the format of an image.
This file contains 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
/** | |
* Return the natural dimensions of an image. | |
* @string img - The image to get the dimensions of. | |
* @return {object} - The natural width of the image. | |
* @return {null} - If the image has no natural dimensions. | |
*/ | |
function getNaturalDimensions({ naturalWidth, naturalHeight }) { | |
// get the image format from the src attribute. | |
let width = naturalWidth; | |
let height = naturalHeight; | |
if (width && height) { | |
// return the natural width and height of the image. | |
return { width, height }; | |
} else { | |
// return null if the image has no natural dimensions. | |
return { width: null, height: null }; | |
} | |
} | |
/** | |
* Return the format of an image. | |
* @string img - The image to get the format of. | |
* @return {string} - The format of the image. | |
* @return {null} - If the image has no format. | |
*/ | |
function getImageFormat(img) { | |
// get the image format from the src attribute. | |
const { width, height } = getNaturalDimensions(img); | |
if (width && height) { | |
if (width > height) { | |
// return landscape if the width is greater than the height. | |
return 'landscape'; | |
} else if (width < height) { | |
// return portrait if width is less than height | |
return 'portrait'; | |
} else if (width === height) { | |
// return square if width and height are equal | |
return 'square'; | |
} else { | |
// return null if the image has no format. | |
return null; | |
} | |
} | |
return null; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment