【问题标题】:How to get image size (height & width) using JavaScript?如何使用 JavaScript 获取图像大小(高度和宽度)?
【发布时间】:2021-05-06 00:39:53
【问题描述】:

是否有任何 JavaScript 或 jQuery API 或方法来获取页面上图像的尺寸?

【问题讨论】:

  • 使用现代浏览器很容易:davidwalsh.name/get-image-dimensions
  • @KamilKiełczewski 这种编辑真的有必要吗?
  • @TylerH 问题与 jquery-plugins 没有直接关系,我认为使用 jquery 标签也允许在答案中使用此类插件(人们经常在没有 lip/plugin 的 JS 问题的答案中使用库/插件标签)。但是,如果您认为回滚我的更改很重要,请随意填写
  • 下面的大多数答案只是获取样式的宽度和高度,而不是实际图像的宽度和高度。使用imgElement.naturalWidthimgElement.naturalHeight 获取宽度和高度。

标签: javascript jquery image


【解决方案1】:

您可以使用 Javascript 以编程方式获取图像并检查尺寸...

const img = new Image();
img.onload = function() {
  alert(this.width + 'x' + this.height);
}
img.src = 'http://www.google.com/intl/en_ALL/images/logo.gif';

如果图像不是标记的一部分,这会很有用。

【讨论】:

【解决方案2】:

clientWidthclientHeight 是 DOM 属性,显示 DOM 元素内部尺寸的当前浏览器内大小(不包括边距和边框)。因此,对于 IMG 元素,这将获得可见图像的实际尺寸。

var img = document.getElementById('imageid'); 
//or however you get a handle to the IMG
var width = img.clientWidth;
var height = img.clientHeight;

【讨论】:

  • @Nicky 完全正确。它给出了图像在该实例中呈现时的尺寸
  • @Mat-visual $.fn.width$.fn.height
  • 正确答案是使用img.naturalWidth和img.naturalHeight
  • document.getElementById 的输入时间更长,但比 $('#...')[0] 快 10 倍。
  • @RexM 在 Chrome 35 上,速度提高了 16 倍:jsperf.com/document-getelementbyid-vs-jquery/5
【解决方案3】:

另外(除了 Rex 和 Ian 的回答)还有:

imageElement.naturalHeight

imageElement.naturalWidth

这些提供图像文件本身的高度和宽度(而不仅仅是图像元素)。

【讨论】:

  • 现在 IE9 和所有现代网络浏览器都支持此功能。
【解决方案4】:

如果您使用的是 jQuery,并且您正在请求图像大小,则必须等到它们加载完毕,否则您只会得到零。

$(document).ready(function() {
    $("img").load(function() {
        alert($(this).height());
        alert($(this).width());
    });
});

【讨论】:

  • 宽度和高度在负载处理程序中是否始终可用?
  • @AndersLindén - 查看 Akseli 为加载事件添加的墨水。有一个专门讨论图像的部分。技术上的回答是“不”,但实际上我的网站使用这种方法从来没有遇到过问题。
  • 但是如果技术回答是否定的,那它就不能用了?不是吗?
  • 图片加载前可以获取属性吗?
【解决方案5】:

我认为更新这些答案很有用,因为投票最多的回复之一建议使用 clientWidth 和 clientHeight,我认为它们现在已经过时了。

我用 HTML5 做了一些实验,看看实际返回了哪些值。

首先,我使用了一个名为 Dash 的程序来大致了解图像 API。 它指出 heightwidth 是图像的渲染高度/宽度,naturalHeightnaturalWidth 是图像的固有高度/宽度(并且仅适用于 HTML5)。

我使用了一个美丽蝴蝶的图像,来自一个高度为 300 和宽度为 400 的文件。还有这个 Javascript:

var img = document.getElementById("img1");

console.log(img.height,           img.width);
console.log(img.naturalHeight,    img.naturalWidth);
console.log($("#img1").height(),  $("#img1").width());

然后我使用了这个 HTML,内联 CSS 用于高度和宽度。

<img style="height:120px;width:150px;" id="img1" src="img/Butterfly.jpg" />

结果:

/*Image Element*/ height == 300         width == 400
           naturalHeight == 300  naturalWidth == 400
/*Jquery*/      height() == 120       width() == 150

/*Actual Rendered size*/    120                  150

然后我将 HTML 更改为以下内容:

<img height="90" width="115" id="img1" src="img/Butterfly.jpg" />

即使用高度和宽度属性而不是内联样式

结果:

/*Image Element*/ height ==  90         width == 115
           naturalHeight == 300  naturalWidth == 400
/*Jquery*/      height() ==  90       width() == 115

/*Actual Rendered size*/     90                  115

然后我将 HTML 更改为以下内容:

<img height="90" width="115" style="height:120px;width:150px;" id="img1" src="img/Butterfly.jpg" />

即同时使用属性和 CSS,看看哪个优先。

结果:

/*Image Element*/ height ==  90         width == 115
           naturalHeight == 300  naturalWidth == 400
/*Jquery*/      height() == 120       width() == 150

/*Actual Rendered size*/    120                  150

【讨论】:

    【解决方案6】:

    使用 JQuery 你可以这样做:

    var imgWidth = $("#imgIDWhatever").width();
    

    【讨论】:

    • 如果图片还没有加载呢?
    【解决方案7】:

    所有其他人都忘记的是,您无法在加载之前检查图像大小。当作者检查所有发布的方法时,它可能只在本地主机上工作。由于这里可以使用 jQuery,请记住在加载图像之前触发 'ready' 事件。 $('#xxx').width() 和 .height() 应该在 onload 事件或之后触发。

    【讨论】:

    • 发布一些更新的代码,您可能会获得点赞,甚至获得梦寐以求的反转徽章!
    【解决方案8】:

    您只能使用加载事件的回调来真正做到这一点,因为图像的大小在实际完成加载之前是未知的。类似于下面的代码...

    var imgTesting = new Image();
    
    function CreateDelegate(contextObject, delegateMethod)
    {
        return function()
        {
            return delegateMethod.apply(contextObject, arguments);
        }
    }
    
    function imgTesting_onload()
    {
        alert(this.width + " by " + this.height);
    }
    
    
    imgTesting.onload = CreateDelegate(imgTesting, imgTesting_onload);
    imgTesting.src = 'yourimage.jpg';
    

    【讨论】:

    • 在 jquery 中,你可以使用 $.proxy。
    【解决方案9】:

    让我们将在这里学到的所有内容组合成一个简单的函数 (imageDimensions())。它使用promises

    // helper to get dimensions of an image
    const imageDimensions = file => 
        new Promise((resolve, reject) => {
            const img = new Image()
    
            // the following handler will fire after the successful loading of the image
            img.onload = () => {
                const { naturalWidth: width, naturalHeight: height } = img
                resolve({ width, height })
            }
    
            // and this handler will fire if there was an error with the image (like if it's not really an image or a corrupted one)
            img.onerror = () => {
                reject('There was some problem with the image.')
            }
        
            img.src = URL.createObjectURL(file)
    })
    
    // here's how to use the helper
    const getInfo = async ({ target: { files } }) => {
        const [file] = files
     
        try {
            const dimensions = await imageDimensions(file)
            console.info(dimensions)
        } catch(error) {
            console.error(error)
        }
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/7.0.0-beta.3/babel.min.js"></script>
    
    Select an image:
    <input
      type="file"
      onchange="getInfo(event)"
    />
    <br />
    <small>It works offline.</small>

    【讨论】:

    • 感谢这段代码,但是对于没有定义宽度和高度属性的 SVG 图像(例如,只设置了 viewBox 的图像),它在 Firefox 中为宽度和高度返回 0。
    • @Crashalot 对,这不适用于矢量图像,仅适用于光栅图像。
    【解决方案10】:

    假设,我们想要得到&lt;img id="an-img" src"..."&gt;的图像尺寸

    // Query after all the elements on the page have loaded.
    // Or, use `onload` on a particular element to check if it is loaded.
    document.addEventListener('DOMContentLoaded', function () {
      var el = document.getElementById("an-img");
    
      console.log({
        "naturalWidth": el.naturalWidth, // Only on HTMLImageElement
        "naturalHeight": el.naturalHeight, // Only on HTMLImageElement
        "offsetWidth": el.offsetWidth,
        "offsetHeight": el.offsetHeight
      });
    
    

    自然尺寸

    el.naturalWidthel.naturalHeight 将得到natural dimensions,即图像文件的尺寸。

    布局尺寸

    el.offsetWidthel.offsetHeight 将为我们提供元素在文档上呈现的尺寸。

    【讨论】:

    • 只需对提供有用内容的现有答案进行投票即可;不要从其中的几个复制到一个新的;那你只是在复制内容。
    【解决方案11】:

    好的伙计们,我想我改进了源代码,以便能够在尝试找出其属性之前让图像加载,否则它将显示“0 * 0”,因为下一条语句将在文件之前被调用已加载到浏览器中。需要 jquery...

    function getImgSize(imgSrc){
        var newImg = new Image();
        newImg.src = imgSrc;
        var height = newImg.height;
        var width = newImg.width;
        p = $(newImg).ready(function(){
            return {width: newImg.width, height: newImg.height};
        });
        alert (p[0]['width']+" "+p[0]['height']);
    }
    

    【讨论】:

      【解决方案12】:

      This 答案正是我想要的(在 jQuery 中):

      var imageNaturalWidth = $('image-selector').prop('naturalWidth');
      var imageNaturalHeight = $('image-selector').prop('naturalHeight');
      

      【讨论】:

        【解决方案13】:

        jQuery库-

        使用.width().height()

        jQuery widthjQuery heigth 中的更多信息。

        示例代码-

        $(document).ready(function(){
            $("button").click(function()
            {
                alert("Width of image: " + $("#img_exmpl").width());
                alert("Height of image: " + $("#img_exmpl").height());
            });
        });
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
        
        <img id="img_exmpl" src="http://images.all-free-download.com/images/graphicthumb/beauty_of_nature_9_210287.jpg">
        <button>Display dimensions of img</button>

        【讨论】:

          【解决方案14】:

          在使用真实图像大小之前,您应该加载源图像。如果您使用 JQuery 框架,您可以通过简单的方式获得真实的图像大小。

          $("ImageID").load(function(){
            console.log($(this).width() + "x" + $(this).height())
          })
          

          【讨论】:

            【解决方案15】:

            认为这可能对 2019 年使用 Javascript 和/或 Typescript 的一些人有所帮助。

            正如一些人所建议的,我发现以下内容不正确:

            let img = new Image();
            img.onload = function() {
              console.log(this.width, this.height) // Error: undefined is not an object
            };
            img.src = "http://example.com/myimage.jpg";
            

            这是正确的:

            let img = new Image();
            img.onload = function() {
              console.log(img.width, img.height)
            };
            img.src = "http://example.com/myimage.jpg";
            

            结论:

            onload 函数中使用img,而不是this

            【讨论】:

            • img.src 上面有一个错字,应该是“ not :我试图编辑这个但不能因为:”编辑必须至少 6 个字符;这篇文章还有什么需要改进的地方吗?”否则一个非常简单的解决方案可以完美运行!
            • 感谢@user2677034 的关注。我没看到。我会责怪苹果的键盘。开个玩笑……这可能是我的错。 ;P
            【解决方案16】:

            获取自然高度和宽度:

            document.querySelector("img").naturalHeight;
            document.querySelector("img").naturalWidth;
            &lt;img src="img.png"&gt;

            如果你想获得样式的高度和宽度:

            document.querySelector("img").offsetHeight;
            document.querySelector("img").offsetWidth;

            【讨论】:

              【解决方案17】:

              jQuery 答案:

              $height = $('#image_id').height();
              $width  = $('#image_id').width();
              

              【讨论】:

                【解决方案18】:

                最近我在 flex 滑块中遇到了同样的问题。由于加载延迟,第一张图片的高度设置得更小。我尝试了以下方法来解决该问题,并且有效。

                // create image with a reference id. Id shall be used for removing it from the dom later.
                var tempImg = $('<img id="testImage" />');
                //If you want to get the height with respect to any specific width you set.
                //I used window width here.
                tempImg.css('width', window.innerWidth);  
                tempImg[0].onload = function () {
                    $(this).css('height', 'auto').css('display', 'none');
                    var imgHeight = $(this).height();
                    // Remove it if you don't want this image anymore.
                    $('#testImage').remove();
                }
                //append to body
                $('body').append(tempImg);
                //Set an image url. I am using an image which I got from google.
                tempImg[0].src ='http://aspo.org/wp-content/uploads/strips.jpg';
                

                这将为您提供相对于您设置的宽度的高度,而不是原始宽度或零。

                【讨论】:

                  【解决方案19】:

                  这是 Node.js 的替代答案,这可能不是 OP 的意思,但可以派上用场,似乎在问题的范围内。

                  这是一个使用 Node.js 的解决方案,该示例使用 Next.js 框架,但适用于任何 Node.js 框架。它使用probe-image-size NPM 包从服务器端解析图像属性。

                  示例用例:我使用以下代码从 Airtable 自动化脚本解析图像的大小,该脚本调用我自己的 analyzeImage API 并返回图像的道具。

                  import {
                    NextApiRequest,
                    NextApiResponse,
                  } from 'next';
                  import probe from 'probe-image-size';
                  
                  export const analyzeImage = async (req: NextApiRequest, res: NextApiResponse): Promise<void> => {
                    try {
                      const result = await probe('http://www.google.com/intl/en_ALL/images/logo.gif');
                  
                      res.json(result);
                    } catch (e) {
                      res.json({
                        error: true,
                        message: process.env.NODE_ENV === 'production' ? undefined : e.message,
                      });
                    }
                  };
                  
                  export default analyzeImage;
                  

                  产量:

                  {
                  "width": 276,
                  "height": 110,
                  "type": "gif",
                  "mime": "image/gif",
                  "wUnits": "px",
                  "hUnits": "px",
                  "length": 8558,
                  "url": "http://www.google.com/intl/en_ALL/images/logo.gif"
                  }
                  

                  【讨论】:

                    【解决方案20】:

                    Nicky De Maeyer 在背景图片后询问;我只是从 css 中获取它并替换“url()”:

                    var div = $('#my-bg-div');
                    var url = div.css('background-image').replace(/^url\(\'?(.*)\'?\)$/, '$1');
                    var img = new Image();
                    img.src = url;
                    console.log('img:', img.width + 'x' + img.height); // zero, image not yet loaded
                    console.log('div:', div.width() + 'x' + div.height());
                    img.onload = function() {
                      console.log('img:', img.width + 'x' + img.height, (img.width/div.width()));
                    }
                    

                    【讨论】:

                    • 在使用 jQuery 时,我从来不理解 regexp 的使用。由于 jQuery 会为您标准化属性,因此您可以使用 s.substr(4,s.length-5) 很好地摆脱它,至少在眼睛上更容易;)
                    【解决方案21】:

                    当页面在 js 或 jquery 中加载时,您可以应用 onload 处理程序属性,如下所示:-

                    $(document).ready(function(){
                       var width = img.clientWidth;
                       var height = img.clientHeight;
                    
                     });
                    

                    【讨论】:

                      【解决方案22】:

                      很简单,你可以这样测试。

                        <script>
                        (function($) {
                              $(document).ready(function() {
                                  console.log("ready....");
                                  var i = 0;
                                  var img;
                                  for(i=1; i<13; i++) {
                                      img = new Image();
                                      img.src = 'img/' + i + '.jpg';
                                      console.log("name : " + img.src);
                                      img.onload = function() {
                                          if(this.height > this.width) {
                                              console.log(this.src + " : portrait");
                                          }
                                          else if(this.width > this.height) {
                                              console.log(this.src + " : landscape");
                                          }
                                          else {
                                              console.log(this.src + " : square");
                                          }
                                      }
                                  }
                              });
                          }(jQuery));
                        </script>
                      

                      【讨论】:

                        【解决方案23】:

                        也许这会对其他人有所帮助。就我而言,我有一个 File 类型(保证是图像)并且我想要图像尺寸而不将其加载到 DOM 上。

                        一般策略:将File 转换为ArrayBuffer -> 将ArrayBuffer 转换为base64 字符串-> 将其用作带有Image 类的图像源-> 使用naturalHeightnaturalWidth 来获取尺寸.

                        const fr = new FileReader();
                        fr.readAsArrayBuffer(image); // image the the 'File' object
                        fr.onload = () => {
                          const arrayBuffer: ArrayBuffer = fr.result as ArrayBuffer;
                        
                          // Convert to base64. String.fromCharCode can hit stack overflow error if you pass
                          // the entire arrayBuffer in, iteration gets around this
                          let binary = '';
                          const bytes = new Uint8Array(arrayBuffer);
                          bytes.forEach(b => binary += String.fromCharCode(b));
                          const base64Data = window.btoa(binary);
                        
                          // Create image object. Note, a default width/height MUST be given to constructor (per 
                          // the docs) or naturalWidth/Height will always return 0.
                          const imageObj = new Image(100, 100);
                          imageObj.src = `data:${image.type};base64,${base64Data}`;
                          imageObj.onload = () => {
                            console.log(imageObj.naturalWidth, imageObj.naturalHeight);
                          }
                        }
                        

                        这允许您从File 获取图像尺寸和纵横比,而无需渲染它。可以使用 fromEvent 轻松地将 onload 函数转换为 RxJS Observables,以获得更好的异步体验:

                        // fr is the file reader, this is the same as fr.onload = () => { ... }
                        fromEvent(fr, 'load')
                        

                        【讨论】:

                          【解决方案24】:

                          我在 jquery 中的两分钱

                          免责声明:这不一定回答这个问题,但会扩大我们的能力。在 jQuery 3.3.1 中测试和工作

                          让我们考虑一下:

                          1. 你有图片的 url/path 并且你想要获取图片的宽度和高度而不在 DOM 上渲染它,

                          2. 在 DOM 上渲染图像之前,您需要将 offsetParent 节点或图像 div 包装器元素设置为图像宽度和高度,以便为不同的图像尺寸创建一个流体包装器,即当单击一个按钮以在模态/灯箱上查看图像时

                          我会这样做:

                          // image path
                          const imageUrl = '/path/to/your/image.jpg'
                          
                          // Create dummy image to get real width and height
                          $('<img alt="" src="">').attr("src", imageUrl).on('load', function(){
                              const realWidth = this.width;
                              const realHeight = this.height;
                              alert(`Original width: ${realWidth}, Original height: ${realHeight}`);
                          })
                          

                          【讨论】:

                            【解决方案25】:

                            你也可以使用:

                            var image=document.getElementById("imageID");
                            var width=image.offsetWidth;
                            var height=image.offsetHeight;
                            

                            【讨论】:

                              【解决方案26】:

                              从父 div 中删除浏览器解释设置很重要。所以如果你想要真实的图像宽度和高度,你可以使用

                              $('.right-sidebar').find('img').each(function(){
                                  $(this).removeAttr("width");
                                  $(this).removeAttr("height");
                                  $(this).imageResize();
                              });
                              

                              这是我的一个 TYPO3 项目示例,我需要图像的真实属性以正确的关系对其进行缩放。

                              【讨论】:

                                【解决方案27】:
                                var imgSrc, imgW, imgH;
                                function myFunction(image){
                                    var img = new Image();
                                    img.src = image;
                                    img.onload = function() {   
                                        return {
                                            src:image,
                                            width:this.width,
                                            height:this.height};
                                        }
                                    return img;
                                }
                                var x = myFunction('http://www.google.com/intl/en_ALL/images/logo.gif');
                                    //Waiting for the image loaded. Otherwise, system returned 0 as both width and height.
                                x.addEventListener('load',function(){
                                    imgSrc = x.src;
                                    imgW = x.width;
                                    imgH = x.height;
                                });
                                x.addEventListener('load',function(){
                                    console.log(imgW+'x'+imgH);//276x110
                                });
                                console.log(imgW);//undefined.
                                console.log(imgH);//undefined.
                                console.log(imgSrc);//undefined.
                                

                                这是我的方法,希望对你有帮助。 :)

                                【讨论】:

                                  【解决方案28】:
                                  function outmeInside() {
                                  var output = document.getElementById('preview_product_image');
                                  
                                   if (this.height < 600 || this.width < 600) {
                                       output.src = "http://localhost/danieladenew/uploads/no-photo.jpg";
                                       alert("The image you have selected is low resloution image.Your image width=" + this.width + ",Heigh=" + this.height + ". Please select image greater or equal to 600x600,Thanks!");
                                   } else {
                                       output.src = URL.createObjectURL(event.target.files[0]);
                                  
                                   }
                                   return;
                                  
                                   }
                                  
                                   img.src = URL.createObjectURL(event.target.files[0]);
                                  }
                                  

                                  这项工作用于多个图像预览和上传。如果您必须一一选择每个图像。然后复制粘贴到所有预览图片功能中并验证!!!

                                  【讨论】:

                                    【解决方案29】:

                                    在获取元素的属性之前,文档页面应该是onload的:

                                    window.onload=function(){
                                        console.log(img.offsetWidth,img.offsetHeight);
                                    }
                                    

                                    【讨论】:

                                      【解决方案30】:

                                      只需传递输入元素获得的img文件对象,当我们选择正确的文件时,它将给出图像的自然高度和宽度

                                      function getNeturalHeightWidth(file) {
                                           let h, w;
                                           let reader = new FileReader();
                                            reader.onload = () => {
                                              let tmpImgNode = document.createElement("img");
                                              tmpImgNode.onload = function() {
                                                h = this.naturalHeight;
                                                w = this.naturalWidth;
                                              };
                                              tmpImgNode.src = reader.result;
                                            };
                                            reader.readAsDataURL(file);
                                          }
                                         return h, w;
                                      }
                                      

                                      【讨论】:

                                        猜你喜欢
                                        • 1970-01-01
                                        • 2013-10-16
                                        • 1970-01-01
                                        • 1970-01-01
                                        • 2013-06-19
                                        • 1970-01-01
                                        • 2017-12-08
                                        相关资源
                                        最近更新 更多