Javascript - 获取图像高度

30 javascript ajax

我需要使用AJAX在网页上显示一堆图像.所有这些都有不同的尺寸,所以我想在显示它们之前调整它们的尺寸.有没有办法在JavaScript中这样做?

getimagesize()对每个图像使用PHP 会导致不必要的性能损失,因为会有很多图像.

小智 77

我正在寻找一种解决方案,使用JavaScript获取图像的高度和宽度.我找到了很多,但所有这些解决方案仅在图像存在于浏览器缓存中时才有效.

最后,我找到了一个解决方案来获取图像的高度和宽度,即使图像在浏览器缓存中不存在:

<script type="text/javascript">

  var imgHeight;
  var imgWidth;

  function findHHandWW() {
    imgHeight = this.height;
    imgWidth = this.width;
    return true;
  }

  function showImage(imgPath) {
    var myImage = new Image();
    myImage.name = imgPath;
    myImage.onload = findHHandWW;
    myImage.src = imgPath;
  }
</script>
Run Code Online (Sandbox Code Playgroud)

谢谢,

Binod Suman

http://binodsuman.blogspot.com/2009/06/how-to-get-height-and-widht-of-image.html

  • 不,`myImage.onLoad = findHHandWW;`是正确的,它在这里传递对函数的引用,而不是调用它并分配结果. (10认同)

Ste*_*ton 21

试试这个:

var curHeight;
var curWidth;

function getImgSize(imgSrc)
{
var newImg = new Image();
newImg.src = imgSrc;
curHeight = newImg.height;
curWidth = newImg.width;

}
Run Code Online (Sandbox Code Playgroud)

  • 此解决方案具有所有正确的部件,但在读取尺寸之前没有给图像加载时间.每个图像的onload事件,也许是一个闭包,都可以使这个工作. (15认同)

Dor*_*ori 0

您想调整图像本身,还是仅调整它们的显示方式?如果是前者,您需要在服务器端进行一些操作。如果是后者,您只需要更改 image.height 和 image.width 即可。