0

我的用户可以上传非常大的图像,并且出于裁剪显示目的,我正在添加width属性,以便它可以很好地适合浏览器窗口。实际图像尺寸可以是 - 比如说 1920 x 1080 像素。

<!-- width added for display purpose -->
<img class="croppable" src="images/fhd.jpg" width="640" />

为了计算真实的选择框尺寸(如果x坐标是 20 像素,那么在原始全高清图片中将是 60 像素),我需要在应用属性之前获取完整的图像尺寸。width

问题是这将返回 640 作为值,考虑到宽度属性:

// Important: Use load event to avoid problems with webkit browser like safari
// when using cached images
$(window).load(function(){
    $('img.croppable').each(function(){
        alert(this.width);
    });
});

请不要将此标记为重复,因为我所要求的与简单的图像宽度/高度检索完全不同(实际上有效)。

编辑:克里斯 G. 解决方案似乎不起作用:

$(window).load(function(){
    $('img.croppable').each(function(){
        console.log(this.src);
        var original = new Image(this.src);
        console.log(original);
        $("#original_w").text(original.width); // Temp, more images to be added
        $("#original_h").text(original.height); // Temp, more images to be added
    });
});

控制台输出:

http://localhost/DigitLifeAdminExtension/images/pillars-of-creation.jpg
<img width="0">
4

4 回答 4

3

获取图像本身的宽度/高度,而不是其中包含的 div。

$(window).load(function(){
    $('img.croppable').each(function(){
        var img = new Image();
        img.src =  $(this).src;
        alert(img.width);
    });
});
于 2011-12-14T22:19:46.180 回答
0

您可以删除属性,获取宽度并再次放置属性:

var $img = $(img);
var oldWidth = $img.attr("width");
var imgWidth = $img.removeAttr("width").width();

$img.width(oldWidth);

但我认为 Chris G. 的答案也很有效,只要确保在您尝试获取宽度时它会被加载:

img.onload = function() {
    if (!img.complete) return; // IMG not loaded
    width = img.width;
   imgManipulationGoesHere();
}
于 2011-12-14T22:31:35.720 回答
0

适用于大多数最新的浏览器和 IE9。

$(window).load(function(){
    $('img.croppable').each(function(){
        alert(this.naturalHeight);
    });
});
于 2011-12-14T22:37:43.923 回答
0

可行的解决方案是:

$(function(){
    $('img.croppable').each(function () {

        var original = new Image(this.src);
        original.onload = function () {
            alert(original.src + ': ' + original.width + 'x' +original.height);
        };
    });
});
于 2011-12-14T22:55:04.970 回答