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.
Created
May 11, 2026 07:16
-
-
Save jeremy-code/8e3d995684b563fd71ebbc4ec4a89986 to your computer and use it in GitHub Desktop.
getImageDimensions()
This file contains hidden or 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
| 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