Skip to content

Instantly share code, notes, and snippets.

@danielhaim1
Last active November 15, 2022 13:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danielhaim1/22658fb489d89660f63ef47407092738 to your computer and use it in GitHub Desktop.
Save danielhaim1/22658fb489d89660f63ef47407092738 to your computer and use it in GitHub Desktop.
Return the format of an image.
/**
* 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