How to check the image file size in jquery?

2019-09-22 02:09发布

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()" />

4条回答
太酷不给撩
2楼-- · 2019-09-22 02:22

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?

查看更多
▲ chillily
3楼-- · 2019-09-22 02:27

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

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

查看更多
Summer. ? 凉城
4楼-- · 2019-09-22 02:33

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.

查看更多
我欲成王,谁敢阻挡
5楼-- · 2019-09-22 02:38

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

查看更多
登录 后发表回答