Javascript-获取图像高度

时间:2020-03-06 14:28:29  来源:igfitidea点击:

我需要使用AJAX在网页上显示一堆图像。它们都具有不同的尺寸,因此我想在显示它们之前调整它们的大小。有没有办法用JavaScript做到这一点?

对每个图像使用PHP的getimagesize()会导致不必要的性能下降,因为将会有很多图像。

解决方案

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

...但是...在服务器端调整图像大小,而不是将字节传输到浏览器并在浏览器中进行操作会更好吗?

当我说调整图像大小时,我并不是说要在HTML图像标签中设置高度和宽度。如果这样做,我们仍将大量字节从服务器传送到客户端。我的意思是,实际上是在服务器端操纵图像本身。

我在这里使用.NET Ccode采取这种方法,但是也必须有一种php方法来做到这一点:http://ifdefined.com/www/gallery.html

另外,通过在服务器端进行操作,这打开了仅进行一次调整然后保存调整后图像的可能性,这将非常快。

好吧...有几种方法可以解释这个问题。

第一种方式和我认为的意思是简单地更改显示尺寸,以便所有图像显示相同的尺寸。为此,我实际上将使用CSS而不是JavaScript。只需创建一个设置了适当的width和height值的类,并使所有的<img>标签都使用该类。

第二种方法是我们要保留所有图像的宽高比,但将显示尺寸缩放为合理的值。有一种方法可以使用JavaScript进行访问,但是我需要一点时间来编写一个快速的代码示例。

第三种方法(希望我们不要这样)是更改图像的实际大小。这是我们必须在服务器端执行的操作,因为JavaScript不仅无法创建图像,而且由于已经发送了完整尺寸的图像,因此没有任何意义。

试试这个:

var curHeight;
var curWidth;

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

}

值得注意的是,在Firefox 3和Safari中,仅通过更改高度和宽度来调整图像大小似乎还不错。在其他浏览器中,它看起来非常吵杂,因为它使用的是最近邻居重采样。当然,我们需要付费以提供更大的图像,但这可能并不重要。

对于这种情况,我的首选解决方案是调整服务器端的大小,这样就可以减少不必要的数据传输。

如果我们必须在客户端执行此操作,并且需要保持图像比例,则可以使用以下方法:

var image_from_ajax = new Image();
image_from_ajax.src = fetch_image_from_ajax(); // Downloaded via ajax call?

image_from_ajax = rescaleImage(image_from_ajax);

// Rescale the given image to a max of max_height and max_width
function rescaleImage(image_name)
{
    var max_height = 100;
    var max_width = 100;

    var height = image_name.height;
    var width = image_name.width;
    var ratio = height/width;

    // If height or width are too large, they need to be scaled down
    // Multiply height and width by the same value to keep ratio constant
    if(height > max_height)
    {
        ratio = max_height / height;
        height = height * ratio;
        width = width * ratio;
    }

    if(width > max_width)
    {
        ratio = max_width / width;
        height = height * ratio;
        width = width * ratio;
    }

    image_name.width = width;
    image_name.height = height;
    return image_name;
}

我正在寻找一种使用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>

谢谢,

比诺德·苏曼(Binod Suman)

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