Quite often when we implement uploading images, will be great to have the opportunity somehow to get image metadata (with, height, fileSize, name ..) in the front-end directly
Example of the input, with uploading the image file:
<input type="file" name="myImage" accept="image/png, image/gif, image/jpeg" onChange={ (e) => handleChange(e.target.files) } />
to get the name, file size and extension of the uploaded file:
const file = e.target.files[0]
const { name } = file
const fileExtension = name.split('.').pop()
const fileSize = file.size
in the case, if needs to get local URL thats used to show render uploaded image:
const localUrl = URL.createObjectURL(file)
To get width, height, of the uploaded image use new FileReader() with image.decode() method:
var reader = new FileReader()
reader.onload = async (e: any) => {
let image = new Image()
image.src = e.target.result
await image.decode()
// now we can:
const width = image.width
const height = image.height
}
reader.readAsDataURL(file)
this is async logic so a better way to use it in a project is to wrap it up with a new Promise, I use the async function wrapper to get all needed metadata:
// Function takes single uploaded img file, and returns width, height, fileSize and fileExtension
export const getImageMeta = async (
file: File
): Promise<{
width: number,
height: number,
fileSize: number,
fileExtension: string,
localUrl: string,
}> => {
const { name } = file
const fileExtension = name.split('.').pop()
const localUrl = URL.createObjectURL(file)
// reading a file to get height and width
async function getImageParams(file: File) {
return new Promise((resolve, reject) => {
var reader = new FileReader()
reader.onload = async (e: any) => {
var image = new Image()
image.src = e.target.result
await image.decode()
resolve({ width: image.width, height: image.height })
}
reader.readAsDataURL(file)
})
}
const { width, height } = await getImageParams(file)
return { width, height, fileSize: file.size, fileExtension, localUrl }
}
Top comments (1)
Thanks