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


当前回答

Try

函数大小(){ console.log(“宽度:${照片。宽度},高度:$ {pic.height}’); } <img id="pic" src="https://picsum.photos/300/150"> <按钮onclick = "尺寸()“>显示> < /按钮大小

其他回答

我想我改进了源代码,以便能够在尝试找出其属性之前让图像加载。否则,它将显示'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']);
}

这个答案正是我所寻找的(在jQuery):

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

clientWidth和clienttheight是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;

Use

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 resolution image. Your image width=" + this.width + ", height=" + 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]);
}

这适用于多个图像预览和上传。如果你必须为每个图像逐一选择,然后复制粘贴到所有预览图像功能和验证!!

最近我有同样的问题,在一个错误的伸缩滑块。由于加载延迟,第一张图像的高度被设置得较小。我尝试了以下方法来解决这个问题,它是有效的。

// Create an 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';

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