【问题标题】:JavaScript: Get image dimensionsJavaScript:获取图像尺寸
【发布时间】:2011-08-03 17:54:14
【问题描述】:

我只有一个图片的 URL。我需要仅使用 JavaScript 来确定此图像的高度和宽度。图像在页面上对用户不可见。我怎样才能得到它的尺寸?

【问题讨论】:

标签: javascript html image


【解决方案1】:

新建一个Image

var img = new Image();

设置src

img.src = your_src

获取widthheight

//img.width
//img.height

【讨论】:

  • 我不断得到 0 的宽度和高度,使用这个确切的代码。
  • 图片好像要加载了,有道理。
  • 附加信息 - 虽然这对我第一次有用,但它是间歇性的。我认为问题是因为图像尚未下载。我通过运行在 onload 事件处理程序中使用维度的代码来修复,如下所示:img.onload = function () {};
  • 只要图像在浏览器缓存中,此代码就可以工作。一旦缓存无效或被删除。它行不通。所以不是很可靠。
  • 这不行,因为图像还没有加载——图像加载是异步完成的,所以你必须等待加载事件。
【解决方案2】:

以下代码为页面上的每个图像添加图像属性heightwidth

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Untitled</title>
<script type="text/javascript">
function addImgAttributes()
{
    for( i=0; i < document.images.length; i++)
    { 
        width = document.images[i].width;
        height = document.images[i].height;
        window.document.images[i].setAttribute("width",width);
        window.document.images[i].setAttribute("height",height);

    }
}
</script>
</head>
<body onload="addImgAttributes();">
<img src="2_01.jpg"/>
<img src="2_01.jpg"/>
</body>
</html>

【讨论】:

  • 问题是关于在不向用户显示图像的情况下获取图像尺寸。在显示图像后设置图像宽度和高度属性绝对没有意义。
【解决方案3】:
var img = new Image();

img.onload = function(){
  var height = img.height;
  var width = img.width;

  // code here to use the dimensions
}

img.src = url;

【讨论】:

  • 除非需要同步获取维度。在这种情况下,您只需将图像插入文档(使用视口外某处的绝对位置) - 然后在调用 document.appendChild() 后立即可以使用尺寸。
  • 为什么onload之前比设置图片的url?
  • @AjayGaur 因为onload 是一个侦听器,如果图像加载正确,它将被异步调用。如果在设置 url 之后设置监听器,图像可能会在代码到达设置 onload 之前加载,导致监听器永远不会被调用。打个比方,如果你给自己端一杯水,你是先倒水,然后再把杯子装满吗?还是先放杯子再倒水?
  • img.naturalWidth 和 img.naturalHeight 是正确答案
  • 谢谢@Kamlesh 我需要自然尺寸。
【解决方案4】:

在此处使用 JQuery 提出和回答的类似问题:

Get width height of remote image from url

function getMeta(url){
  $("<img/>").attr("src", url).load(function(){
     s = {w:this.width, h:this.height};
     alert(s.w+' '+s.h);      
  }); 
}

getMeta("http://page.com/img.jpg");

【讨论】:

    【解决方案5】:

    这会使用该函数并等待它完成。

    http://jsfiddle.net/SN2t6/118/

    function getMeta(url){
        var r = $.Deferred();
    
      $('<img/>').attr('src', url).load(function(){
         var s = {w:this.width, h:this.height};
         r.resolve(s)
      });
      return r;
    }
    
    getMeta("http://www.google.hr/images/srpr/logo3w.png").done(function(test){
        alert(test.w + ' ' + test.h);
    });
    

    【讨论】:

    • 为什么这个带有延迟的可重用函数会被否决?!
    • '仅使用 JavaScript' 我猜这是 jQuery
    • 尽管它使用的是 jQuerry,但你还是得到了我的支持。方法很重要。
    【解决方案6】:

    naturalWidthnaturalHeight

    var img = document.createElement("img");
    img.onload = function (event)
    {
        console.log("natural:", img.naturalWidth, img.naturalHeight);
        console.log("width,height:", img.width, img.height);
        console.log("offsetW,offsetH:", img.offsetWidth, img.offsetHeight);
    }
    img.src = "image.jpg";
    document.body.appendChild(img);
    
    // css for tests
    img { width:50%;height:50%; }
    

    【讨论】:

      【解决方案7】:

      使用 jQuery 获取图像大小

      function getMeta(url){
          $("<img/>",{
              load : function(){
                  alert(this.width+' '+this.height);
              },
              src  : url
          });
      }
      

      使用 JavaScript 获取图像大小

      function getMeta(url){   
          var img = new Image();
          img.onload = function(){
              alert( this.width+' '+ this.height );
          };
          img.src = url;
      }
      

      使用 JavaScript(现代浏览器、IE9+)获取图像大小

      function getMeta(url){   
          var img = new Image();
          img.addEventListener("load", function(){
              alert( this.naturalWidth +' '+ this.naturalHeight );
          });
          img.src = url;
      }
      

      将上面的内容简单地用作:getMeta("http://example.com/img.jpg");

      https://developer.mozilla.org/en/docs/Web/API/HTMLImageElement

      【讨论】:

        【解决方案8】:

        如果您有输入表单中的图像文件。 你可以这样使用

        let images = new Image();
        images.onload = () => {
         console.log("Image Size", images.width, images.height)
        }
        images.onerror = () => result(true);
        
        let fileReader = new FileReader();
        fileReader.onload = () => images.src = fileReader.result;
        fileReader.onerror = () => result(false);
        if (fileTarget) {
           fileReader.readAsDataURL(fileTarget);
        }
        

        【讨论】:

          【解决方案9】:

          结合 Promise 和打字稿输入:

          /**
           * Returns image dimensions for specified URL.
           */
          export const getImageDimensions = (url: string): Promise<{width: number, height: number}> => {
            return new Promise((resolve, reject) => {
              const img = new Image();
              img.onload = () => resolve({
                width: img.width,
                height: img.height,
              });
              img.onerror = (error) => reject(error);
              img.src = url;
            });
          };
          

          用法:

          try {
            const {width, height} = await getImageDimensions(entry.NWS_IMAGE);
            console.log(`Image dimensions: ${width}px x ${height}px`);
          } catch (e) {
            // Could not load image from specified URL
            console.error(e);
          }
          

          【讨论】:

            猜你喜欢
            • 2015-03-27
            • 1970-01-01
            • 1970-01-01
            • 2011-11-19
            • 2018-07-31
            • 2012-02-11
            • 2011-04-22
            • 1970-01-01
            相关资源
            最近更新 更多