the-front-end-knowledge-you-may-not-know icon indicating copy to clipboard operation
the-front-end-knowledge-you-may-not-know copied to clipboard

获取图片原始尺寸

Open chbro opened this issue 6 years ago • 7 comments

let getImgRawSize = (img, cb) => {
    img = img || document.querySelector(img)
    if (!img instanceof HTMLImageElement) {
        return console.log(`error getting ${img} dom`)
    }

    if (img.naturalWidth) {
        return cb({width: img.naturalWidth, height: img.naturalHeight})
    }
    if (img.complete) {
        return cb({width: img.width, height: img.height})
    }
    let _image = new Image
    _image.src = img.src
    _image.onload = _ => {
        cb({width: _image.width, height: _image.height})
    }
}

chbro avatar Nov 08 '18 01:11 chbro

第一行代码就错了吧。。

Dcatfly avatar Nov 08 '18 08:11 Dcatfly

之前也写过一篇,不借助ImageElement的 https://github.com/iamgqb/I-should-know/issues/2

iamgqb avatar Jan 19 '19 08:01 iamgqb

其实 onload 事件需要设置在 _image.src = img.src 语句之前

ghost avatar Jan 28 '19 17:01 ghost

其实 onload 事件需要设置在 _image.src = img.src 语句之前

这里js执行比发起网络请求要快,所以不会影响吧。但放到前面会保险一些

chbro avatar Feb 13 '19 01:02 chbro

如果 image 的width,height被设置,是不准确的。

<img src="path.png" width="100" height="100" alt="image" />

or

const image = new Image()
image.width = 100
image.height = 100
image.src = 'path.png'

应该只能依据img.naturalWidth或者new Image()来判断

export default function(image: HTMLImageElement) {
  return new Promise((resolve, reject) => {
    if (image.naturalWidth) {
      resolve({ width: image.naturalWidth, height: image.naturalHeight })
    }
    const savedImage = new Image()
    savedImage.onload = () => {
      resolve({ width: savedImage.width, height: savedImage.height })
    }
    savedImage.onerror = err => {
      reject(err)
    }
    savedImage.src = image.src
  })
}

xg4 avatar Feb 28 '19 08:02 xg4

img = img || document.querySelector(img)

这句应该是不对的吧。看上去像是支持 DOM 和 选择器,但是其实并不会执行选择器部分。

img = img || document.querySelector('img')

或者是直接删掉?或者是应该判断是img是字符串,然后就去querySelector

github-linong avatar Nov 26 '20 09:11 github-linong

@github-linong 是的。 工作两年半后,来更新下代码


function getImgRawSize(img: HTMLImageElement | string): Promise<{ width: number; height: number }> {
  const $img: HTMLImageElement = typeof img === 'string' ? document.querySelector(img) : img;

  return new Promise((resolve, reject) => {
    if ($img.naturalWidth) {
      resolve({ width: $img.naturalWidth, height: $img.naturalHeight });
    }
    if ($img.complete && !$img.getAttribute('width') && !$img.getAttribute('height')) {
      resolve({ width: $img.width, height: $img.height });
    }

    const image = new Image;
    image.onload = () => {
      resolve({ width: image.width, height: image.height })
    }
    image.onerror = reject;
    image.src = $img.src;
  })
}

chbro avatar Nov 26 '20 13:11 chbro