简体   繁体   中英

Get Image Height according to width in .load()

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

$('<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

$('<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.

Thanks In Advance :)

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

})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM