Skip to content

Instantly share code, notes, and snippets.

@jeremy-code
Created May 11, 2026 07:16
Show Gist options
  • Select an option

  • Save jeremy-code/8e3d995684b563fd71ebbc4ec4a89986 to your computer and use it in GitHub Desktop.

Select an option

Save jeremy-code/8e3d995684b563fd71ebbc4ec4a89986 to your computer and use it in GitHub Desktop.
getImageDimensions()

getImageDimensions TypeScript function using Image constructor and onLoad/onError. Much faster than Window.createImageBitmap. Uses imageOrientation = "from-image" to set width and height based on Exif data.

const getImageDimensions = async (image: Blob | MediaSource) => {
return new Promise((resolve, reject) => {
const imageElement = new Image();
imageElement.style.imageOrientation = "from-image";
const objectUrl = URL.createObjectURL(image);
imageElement.onload = () => {
URL.revokeObjectURL(objectUrl);
resolve({
width: imageElement.naturalWidth,
height: imageElement.naturalHeight,
});
};
imageElement.onerror = (event, _, __, ___, error) => {
URL.revokeObjectURL(objectUrl);
reject(
error !== undefined ? error
: typeof event === "string" ? new Error(event)
: new Error("Unknown error"),
);
};
});
};
export { getImageDimensions };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment