How to check the image file size in jquery?

2019-09-22 02:18发布

问题:

I have a button while clicking that button I need to get the image file size

function attachPhoto()
{
    var path="http://www.w3schools.com/images/pulpit.jpg";// i need to check size of image
}

<input type="button" style="width:30%" onClick=" attachPhoto()" />

回答1:

$('image').width() and $('image').height()

Only after it has fully loaded (maybe attach it to the .load() event).



回答2:

$('element').width() or $('element').height()



回答3:

If you want to get the dimensions of a file using only a URL, you need to use an external language like PHP. jQuery can't retrieve file properties.

One way of doing it would be to load the image somewhere offscreen and get the $('image').width() & $('image').height() but it's not an ideal way.

The best way would be to use an ajax call to a php script that would check the dimensions of the file and return it to jQuery.

Do you have access to a php server?



回答4:

Here's a non-jQuery solution:

function attachPhoto() {
    var img = new Image();
    img.onload = function() {
        alert([img.width, img.height]);
    } 
    img.src = "http://www.w3schools.com/images/pulpit.jpg";
}

Note that the image size will only be available once the file is loaded, and the onload callback will be called asynchronously. If you want other stuff to happen once you know the size that must be triggered from inside that callback.