前端获取图片的尺寸

588 阅读1分钟
 * @description: 获取图片的大小
 * @param {*} src 图片的路径
 * @return {*}
 */
export const getImgSize = (src) => {
  return new Promise((resolve, reject) => {
    const img = new Image();
    img.src = src;
    img.onload = (data) => {
      let imgEl = null;
      if (data.path) {
        imgEl = data.path[0];
      } else {
        imgEl = data.target;
      }
      if (imgEl.naturalWidth) {
        const obj = {
          width: imgEl.naturalWidth,
          height: imgEl.naturalHeight
        };
        resolve(obj);
      } else {
        reject();
      }
    };
  });
};

tip 生成预览url

window.URL.createObjectURL(file);