Let's combine everything we learned here into one simple function (imageDimensions()
). It uses promises.
// helper to get dimensions of an image
const imageDimensions = file =>
new Promise((resolve, reject) => {
const img = new Image()
// the following handler will fire after the successful loading of the image
img.onload = () => {
const { naturalWidth: width, naturalHeight: height } = img
resolve({ width, height })
}
// and this handler will fire if there was an error with the image (like if it's not really an image or a corrupted one)
img.onerror = () => {
reject('There was some problem with the image.')
}
img.src = URL.createObjectURL(file)
})
// here's how to use the helper
const getInfo = async ({ target: { files } }) => {
const [file] = files
try {
const dimensions = await imageDimensions(file)
console.info(dimensions)
} catch(error) {
console.error(error)
}
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/7.0.0-beta.3/babel.min.js"></script>
Select an image:
<input
type="file"
onchange="getInfo(event)"
/>
<br />
<small>It works offline.</small>
_x000D_