jQuery:如何获取外部图像的尺寸

jQuery: how to get the dimensions of a external image?

本文关键字:图像 外部 获取 何获取 jQuery      更新时间:2023-09-26

寻找一种获取外部图像尺寸(宽度和高度)的方法。
我使用了prop()attr(),但它们不返回任何值。只是一个错误。

例:

<a href="pathtotheimage">some link</a>

jQuery

var path = 'https://source.unsplash.com/random/600x300/?montreal';
$("<img/>").attr('src', path).load(function() {
    console.log(this.width, this.height);
 });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>

香草Javascript

var path = 'https://source.unsplash.com/random/600x300/?montreal';
var img = new Image();
img.src = path;
img.addEventListener('load', function() {
  console.log(this.width, this.height);
});

看起来没有人提供有效的香草 js 答案。

var img = document.createElement('img')
img.src = 'http://domain.com/img.png'
img.onload = function() {
    console.log( this.width )
    console.log( this.height )
}

这是一个jsfiddle:http://jsfiddle.net/Ralt/VMfVZ/

从技术上讲,这不是jQuery,但我会走以下路线:

var image = new Image(), width, height;
image.src = 'http://whereyourimage.is/heresmyimage.jpg';
width = image.width;
height = image.height;

然后,您可以使用 widthheight 访问这些值,例如alert('My image is ' + width + ' pixels accross.');