在前端开发中咱们简直不须要获取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> //jsPage({ 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>

到此结束,大家有问题欢送到评论区探讨。

文章首发于我的博客-《JavaScript获取img的原始尺寸》