JavaScript獲取img的原始尺寸

來了老弟發表於2023-03-26
在前端開發中我們幾乎不需要獲取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>

到此結束,大家有問題歡迎到評論區討論。

文章首發於我的部落格-《JavaScript獲取img的原始尺寸》

相關文章