如何通过JavaScript获取图像的宽度和高度(cm)? 我写了一个简单的脚本,但是当图像具有不同的分辨率时,它就无法显示正确的w和h。 请帮我。 (对不起我的英文)
答案 0 :(得分:0)
$('img').width();
$('img').height();
或
$('img').clientWidth;
$('img').clientHeight;
答案 1 :(得分:0)
使用像素到厘米转换器的纯JavaScript上的小样本(大小取决于屏幕的DPI):
var
getSizeInCM,
ready;
/* Convert px to cm */
getSizeInCM = function(sizeInPX) {
return sizeInPX * 2.54 / (96 * window.devicePixelRatio)
};
ready = function() {
var
img = document.getElementById('img'),
width = getSizeInCM(img.clientWidth),
height = getSizeInCM(img.clientHeight);
alert('width: ' + width.toFixed(2) + ' cm, height: ' + height.toFixed(2) + ' cm');
};

<body onload="ready()">
<img id="img" src="http://placehold.it/250x150">
</body>
&#13;
结果(MacBook Pro 2011年末,Google Chrome):
结果(Apple Iphone 6,Safari):
答案 2 :(得分:0)
如果足以假设每英寸96像素,则公式是计算cm
是:
centimeters = pixels * 2.54 / 96
function getImgSize() {
var img = document.getElementById('img');
var width = img.clientWidth * 2.54 / 96;
var height = img.clientHeight * 2.54 / 96;
document.getElementById('demo').innerHTML = 'width: ' + width + ', height: ' + height;
};
<body onload="getImgSize()">
<img id="img" src="http://placehold.it/250x150">
<p id="demo"></p>
</body>
答案 3 :(得分:0)
使用HTML5进行一些实验,以查看实际返回的值。
首先,我使用了一个名为Dash的程序来概述图像API。它说明了&#39;身高&#39;和#&#39;宽度&#39;是图像的渲染高度/宽度和自然高度&#39;和&#39; naturalWidth&#39;是图像的固有高度/宽度(仅限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" />
i.e. using both attributes and CSS, to see which takes precedence.
结果:
/*Image Element*/ height == 90 width == 115
naturalHeight == 300 naturalWidth == 400
/*Jquery*/ height() == 120 width() == 150
/*Actual Rendered size*/ 120 150
注意:我已从Height and Width复制了此答案。真的值得了解这些差异。
希望这会对你有所帮助。