获得真实的图像宽度和高度

时间:2013-11-26 21:32:44

标签: javascript

当我使用image.width时,它会返回屏幕上显示的图片宽度,并在图片上使用max-width属性,该图片会显示在某些div中。真实图像的大小要大得多。是否有可能获得真实图像的宽度?

5 个答案:

答案 0 :(得分:2)

您可以通过创建具有相同来源的新图像并获取其尺寸来获取图像的实际尺寸

var img = new Image();

img.onload = function() {
    var w = this.width,
        h = this.height;
}

img.src = $('img')[0].src; // or whatever

FIDDLE

答案 1 :(得分:0)

首先,要知道图像是异步加载的,这意味着您必须编写代码,以便在回调函数中获得结果。然后,使用没有显式样式的新图像对象(因此可以调整大小以适应本机图像尺寸)以触发回调。例如:

function whatWidth(url, onSize) {
  var img = new Image();
  img.src = url;
  img.onload = function() {
    onSize(img.width, img.height);
  }
}

// Now get the dimensions of an image ...
whatWidth('http://icons.iconarchive.com/icons/deleket/keriyo-emoticons/256/Smiley-rofl-icon.png',
  function(w, h) {
    console.log('width x height: ', w, h);
  }
);

// => Outputs "width x height: 256 256"

值得注意的是,虽然这似乎需要服务器获取图像的请求(独立于您实际在网页上显示的任何图像对象),只要该网址与网址相同即可。在您的页面上,浏览器缓存将[通常]确保只发出一个请求。

答案 2 :(得分:0)

Dart示例,如果您需要缓存(我知道原始问题提到JS,但逻辑保持不变):

class _IconSize {
  final int width;
  final int height;

  _IconSize(this.width, this.height);
}


class IconLoader {
  static final IconLoader _this = new IconLoader._init();
  factory IconLoader() => _this;

  // Url -> dimensions.
  final Map<String, _IconSize> _cache = {};

  IconLoader._init() {}

  void withSize(String url, void onLoaded(int width, int height)) {
    if (_cache.containsKey(url)) {
      onLoaded(_cache[url].width, _cache[url].height);

    } else {
      final ImageElement img = new ImageElement();
      img.onLoad.listen((_) {
        var iconSize = new _IconSize(img.width, img.height);
        _cache[url] = iconSize;
        withSize(url, onLoaded);
      });
      img.src = url;
    }
  }
}

答案 3 :(得分:0)

结果是有一个def adding_report(): report_value = input('Input an integer to add to the total or "Q" to quit: ') while True: if report_value == "": report_value = input('Input an integer to add to the total or "Q" to quit: ') elif report_value.isdigit(): final_value = int(report_value) + int(report_value) elif report_value.lower() == "q": break adding_report() 属性。 FULLWIDTH COLON

答案 4 :(得分:-1)

您需要在图片的onload事件

上访问它

<强> JS

  var testImg = document.getElementById('testImg'), 
    iWidth=document.getElementById('width'),
    iHeight =    document.getElementById('height');

    testImg.onload = function(){
        console.log(this);
        iWidth.value=this.width;
        iHeight.value=this.height;
    };

以下是jsfiddle:http://jsfiddle.net/mac1175/evgP8/

相关问题