Skip to content

Instantly share code, notes, and snippets.

@guillermodlpa
Created June 27, 2023 09:12
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 guillermodlpa/2391a752466042e5570636bcfab5a164 to your computer and use it in GitHub Desktop.
Save guillermodlpa/2391a752466042e5570636bcfab5a164 to your computer and use it in GitHub Desktop.
/**
* Get the dimensions of an image file
* Check the mime type before calling this function
*/
export default function getImageFileDimensions(
imageFile: File,
): Promise<{ width: number; height: number }> {
return new Promise((resolve, reject) => {
if (!(window.File && window.FileReader && window.FileList && window.Blob)) {
reject(
new Error('The File APIs are not fully supported in this browser.'),
);
return;
}
const reader = new FileReader();
reader.onload = function () {
const img = new Image();
img.onload = function () {
// image is loaded; sizes are available
const { width, height } = img;
resolve({ width, height });
};
img.onerror = function () {
reject(new Error('There was an error loading the image'));
};
if (!reader.result) {
reject(new Error('No reader result'));
return;
}
img.src = reader.result.toString();
};
reader.readAsDataURL(imageFile);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment