简体   繁体   中英

How do i get the image dimensions (height, width) from a file by using javascript

I am probably being very very stupid. But i cant get this to work for my life. I am trying to set the imgWidth to the same width as the image width of the file (pic_real_width).

function calculate() {
    var pic_real_width, pic_real_height;
    $("<img/>").attr("src", $("#pp_photo_popUp")[0].src).load(function() {
        pic_real_width = this.width;   // Note: $(this).width() will not
        pic_real_height = this.height; // work for in memory images.
    });
    var imgWidth = 
}

All in all I am trying to make a function to get the real dimensions of a file on the hard disk.

Bind the load event First, and then do all processing that needs the image to be loaded inside of the load event.

function calculate(callback) {
    $("<img/>").load(function() {
        var pic_real_width = this.width;   // Note: $(this).width() will not
        var pic_real_height = this.height; // work for in memory images.
        callback(pic_real_width,pic_real_height);
    }).attr("src", $("#pp_photo_popUp")[0].src);
}

calculate(function(width,height) {
    console.log(width,height);
});

If you set the src first, some versions of IE will immediately trigger the load event synchronously, thus triggering it before you have even bound to it. That's why i swapped the order. Additionally, I added the callback parameter because I assume later in the function you were going to return the width/height, which won't work due to the asynchronous nature of load events.

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