How to get image size (height & width) using JavaScript?

前端 未结 29 2986
忘了有多久
忘了有多久 2020-11-21 05:23

Are there any JavaScript or jQuery APIs or methods to get the dimensions of an image on the page?

29条回答
  •  难免孤独
    2020-11-21 05:45

    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)
        }
    }
    
    
    Select an image:
    
    
    It works offline.

提交回复
热议问题