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


当前回答

const file = event.target.files[0];
const img = new Image();
img.onload = function () {
  width = img.width;
  height = img.height;
};
img.src = URL.createObjectURL(file);
alert(width + "x" + height);

其他回答

您可以通过编程方式获取图像并使用JavaScript检查尺寸…

const img = new Image(); img。Onload = function() { 警报(这。Width + 'x' + this.height); } img。src = 'http://www.google.com/intl/en_ALL/images/logo.gif';

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

简单地说,您可以像这样进行测试。

  <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>
var img = document.getElementById("img_id");
alert( img.height + " ;; " + img .width + " ;; " + img .naturalHeight + " ;; " + img .clientHeight + " ;; " + img.offsetHeight + " ;; " + img.scrollHeight + " ;; " + img.clientWidth + " ;; " + img.offsetWidth + " ;; " + img.scrollWidth )
//But all invalid in Baidu browser  360 browser ...

jQuery的答案:

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

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

// helper to get dimensions of an image const imageDimensions = file => new Promise((resolve, reject) => { const img = new Image() // the following handler will fire after a 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>