Interview question: JS get picture width and height

Time:2021-1-26

Generally used in the audit background, for exampleThe image can only be refined within a certain range
It is also used for clipping in canvasCalculate scaling

JS get image width and height

Get naturalwidth (callback version)

The solution is to getnaturalWidth. thatnaturalWidthandwidthAny difference?

  • naturalWidthIdentifies the original width and height of the picture.
  • widthBecause of historical problems, it is the width and height of DOM elements that are identified.
  • Because the IMG tag will be spread by the image, so

    • When the width property is not set,width == naturalWidth
    • When the width property is set,width != naturalWidth
getImgRawSize = (img, cb) => {
    var _image = img;
    if (_image instanceof HTMLImageElement) {
        //The DOM object is passed in
        if (_image.naturalWidth) {
            //It is recommended to use naturalwidth because it returns the original value and will not be affected by the attribute
            return cb({width: _image.naturalWidth, height: _image.naturalHeight})
        }
        if (_image.complete) {
            //If there is no naturalwidth and the image has been loaded, there is a high probability that it is not supported
            //To prevent being affected by attributes, we need to reload with a blank tag
            img = img.src
        }else{
            //If the loading is not completed, use it directly
            _image = img;
        }
    }
    if(typeof img == 'string'){
        //The URL is passed in
        _image = new Image();
        _image.src = img
    }
    _image.onload = _ => {
        //If you want to be secure, you can consider that if you can't get the naturalwidth, you just use the new image to get it
        cb({width: _image.naturalWidth || _image.width, height: _image.naturalHeight||_image.height})
    }
    _image.onerror = _ => {
        cb({width: 0, height: 0})
    }
}

Test screenshot

Interview question: JS get picture width and height

test case

getImgRawSize('https://www.lilnong.top/static/img/ml-active-btn1.png', v=>console.log(1, v))
getImgRawSize('https://www.lilnong.top/static/img/ml-active-btn6.png', v=>console.log(2, v))

//Test not loaded
img = new Image()
img.src = 'https://www.lilnong.top/static/img/defaultmatch.png'
getImgRawSize(img, v=>console.log(3,v))


//Test not loaded且设置宽高
img = new Image()
img.width = 10
img.height = 20
img.src = 'https://www.lilnong.top/static/img/QQ_20190301172837.jpg'
getImgRawSize(img, v=>console.log(4,v))


//Test loaded
img = new Image()
img.src = 'https://www.lilnong.top/static/img/Rectangle%2010.png'
img.onload = ()=>getImgRawSize(img, v=>console.log(5,v))

//Test loaded且设置宽高
img = new Image()
img.width = 10
img.height = 20
img.src = 'https://www.lilnong.top/static/img/ml-btn6.png'
img.onload = ()=>getImgRawSize(img, v=>console.log(6,v))

Get naturalwidth (promise version)

The implementation is the same as above, except for the promise version.

getImgRawSize = (img) => {
    return Promise.resolve(new Promise(function(reslove, reject){
        var _image = img;
        if (_image instanceof HTMLImageElement) {
            if (_image.naturalWidth) return reslove({width: _image.naturalWidth, height: _image.naturalHeight})
            img = img.src
        }
        if(typeof img == 'string'){
            _image = new Image();
            _image.src = img
        }
        _image.onload = _ =>  reslove({width: _image.naturalWidth || _image.width, height: _image.naturalHeight||_image.height})
        _image.onerror = _ =>  reject({width: 0, height: 0})
    }))
}

Test screenshot

Interview question: JS get picture width and height

test case

getImgRawSize('https://www.lilnong.top/static/img/ml-active-btn1.png').then(v=>console.log(1, v))
getImgRawSize('https://www.lilnong.top/static/img/ml-active-btn6.png').then(v=>console.log(2, v))

//// test not loaded
img = new Image()
img.src = 'https://www.lilnong.top/static/img/defaultmatch.png'
getImgRawSize(img).then(v=>console.log(3, v))


//The test is not loaded and the width and height are set
img = new Image()
img.width = 10
img.height = 20
img.src = 'https://www.lilnong.top/static/img/QQ_20190301172837.jpg'
getImgRawSize(img).then(v=>console.log(4, v))


//Test loaded
img = new Image()
img.src = 'https://www.lilnong.top/static/img/Rectangle%2010.png'
img.onload = ()=>getImgRawSize(img).then(v=>console.log(5, v))

//Test loaded且设置宽高
img = new Image()
img.width = 10
img.height = 20
img.src = 'https://www.lilnong.top/static/img/ml-btn6.png'
img.onload = ()=>getImgRawSize(img).then(v=>console.log(6, v))