根据.load()中的宽度获取图像高度

时间:2022-12-15 18:58:46

I need to get Image height and width before loading the Image itself. So I am using jquery .load() method.

我需要在加载Image本身之前获取Image高度和宽度。所以我使用的是jquery .load()方法。

$('<img />').attr('src',someURL).load(function(){
  console.log(this.width);
  console.log(this.height);
})

But problem is that I need the height according to the fix width. Suppose Image is of size 400*417, I need the height according to 200 not 400. For that I add

但问题是我需要根据固定宽度的高度。假设图像的大小为400 * 417,我需要根据200而不是400的高度。为此我添加

$('<img />').attr({
'src':someURL,
'width':200}).load(function(){
  //Get height and width
})

But Above code is again giving me height 417 not according to width of 200. I am looking for js/jquery/angualrjs. Please help.

但是上面的代码再次给我高度417而不是宽度为200.我正在寻找js / jquery / angualrjs。请帮忙。

Thanks In Advance :)

提前致谢 :)

1 个解决方案

#1


2  

A bit of math will do the trick. Once you get the actual image dimensions, apply your ratio to get the height you want.

一点数学就能解决问题。获得实际图像尺寸后,应用比率以获得所需的高度。

For instance :

例如 :

$('<img />').attr('src',someURL).load(function(){
  console.log(this.width); // prints out 400
  console.log(this.height); // prints out 417

  var widthIWant = 200;

  var heightIWant = this.height * widthIWant / this.width; // Gives you 208.5

})

#1


2  

A bit of math will do the trick. Once you get the actual image dimensions, apply your ratio to get the height you want.

一点数学就能解决问题。获得实际图像尺寸后,应用比率以获得所需的高度。

For instance :

例如 :

$('<img />').attr('src',someURL).load(function(){
  console.log(this.width); // prints out 400
  console.log(this.height); // prints out 417

  var widthIWant = 200;

  var heightIWant = this.height * widthIWant / this.width; // Gives you 208.5

})