在Javascript中获取图像的高度/宽度(理想情况下根本不加载图像) [英] Get height/width of image in Javascript (ideally without loading the image at all)

查看:32
本文介绍了在Javascript中获取图像的高度/宽度(理想情况下根本不加载图像)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对不起,如果已经回答了,但是我找不到.

Sorry if this has already been answered, but I can't find it if so.

我想用Javascript查找图像文件的高度和宽度.我实际上不需要在页面中显示图像,只需显示高度和宽度即可.

I want to find the height and width of an image file in Javascript. I don't actually need to show the image in the page, just the height and width.

目前,我有以下代码,但返回的高度和宽度为0(在Mozilla 5中).

At the moment I've got the following code, but it's returning height and width 0 (in Mozilla 5).

  var img = new Image();
  img.src = "./filename.jpg";
  var imgHeight = img.height;
  var imgWidth = img.width;
  alert("image height = "  + imgHeight + ", image width = " + imgWidth);

该文件确实存在,与HTML位于同一目录中,并且高度和宽度都不为0:)

The file definitely exists, it's in the same directory as the HTML, and it doesn't have height and width 0 :)

我在做什么错了?

推荐答案

如果未加载图像,则不会设置其高度和宽度.您必须等到图像完全加载后,再检查其尺寸.也许遵循以下原则:

If the image is not loaded, it won't have its' height and width set. You have to wait until the image is fully loaded, then inspect its' size. Maybe something along these lines:

function getWidthAndHeight() {
    alert("'" + this.name + "' is " + this.width + " by " + this.height + " pixels in size.");
    return true;
}
function loadFailure() {
    alert("'" + this.name + "' failed to load.");
    return true;
}
var myImage = new Image();
myImage.name = "image.jpg";
myImage.onload = getWidthAndHeight;
myImage.onerror = loadFailure;
myImage.src = "image.jpg";

这篇关于在Javascript中获取图像的高度/宽度(理想情况下根本不加载图像)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆