在前端开发中我们几乎不需要获取img的原始尺寸,因为只要你不刻意设置图片的宽高它都会按照最佳比例渲染。但是在微信小程序开发时,它的image标签有一个默认高度,这样你的图片很可能出现被压缩变形的情况,所以就需要获取到图片的原始尺寸对image的宽高设置。

微信小程序获取image原始尺寸的方法

<view style="width:100%;" >
 <image src="https://sf3-ttcdn-tos.pstatp.com/img/mosaic-legacy/3796/2975850990~300x300.image" bindload="loadSuccess" style="width:{{imageWidth}}px; height:{{imageHeight}}px"></image>
</view>
//js
Page({
 data: {
  imageHeight: 0,
  imageWidth: 0
 },
 loadSuccess(e){
  const { detail: {width, height} } = e // // 这里获取到的就是图片原始尺寸
  this.setData({
    imageWidth: width,
    imageHeight:height
  })
 }
})

wx.getImageInfo

方法是wx.getImageInfo,微信官方文档 这个需要添加业务域名,服务端做接口验证。比较繁琐不推荐。

浏览器中获取图片尺寸的方法

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>img原始尺寸获取</title>
  <style>
    .image {
      /* height:  20px;  这种写法没什么卵用 */ 
    }
  </style>
</head>
<body>
  <img class="image" referrerpolicy="no-referrer" src="https://image-static.segmentfault.com/193/916/1939169050-641cff9f16cdc_fix732"
       style="width: 300px;">

  <script>
    // 1. 获取DOM元素的渲染尺寸
    const img = document.querySelector('.image');
    console.log(img.style.width)  // 300px 获取到字符串
    console.log(img.style.height) // 如果在标签行内样式没有设置 无法获取到

    // 2. 直接获取DOM元素的width和height属性
    console.log(img.width)        // 300 获取到的数字类型
    console.log(img.height)       // 533 可以获取到元素的渲染高度

    // 3. naturalWidth / naturalHeight (适用于Firefox/IE9/Safari/Chrome/Opera浏览器)
    console.log('naturalWidth:', img.naturalWidth)   // naturalWidth: 412
    console.log('naturalHeight:', img.naturalHeight) // naturalHeight: 732

    // 4. 使用Image()对象异步获取图片原始尺寸
    function getImageInfo(url) {
      return new Promise((resolve, reject) => {
        let image = new Image();
        image.onload = () => {
          resolve({
            width: image.width,
            height: image.height
          })
        }

        image.onerror = () => {
          reject(new Error('image load error'))
        }

        image.src = url;
      })
    }

    (async () => {
      let size = await getImageInfo('https://image-static.segmentfault.com/193/916/1939169050-641cff9f16cdc_fix732')
      console.log(size) // {width: 412, height: 732}
    })()

    // 终极兼容写法 (首先检测浏览器是否支持img.naturalWidth,如果支持直接获取,不支持使用4.Image()对象获取)
    async function getImageSize(img) {
      if (img.naturalWidth) {
        return {
          width: img.naturalWidth,
          height: img.naturalHeight
        }
      } else {
        return await getImageInfo(img.src)
      }
    }
  </script>
</body>
</html>
原文地址:https://segmentfault.com/a/1190000043578972