Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine image size in JavaScript without `<img>` tag

Using JavaScript, how can I determine the size of an image which is not in the document without inserting it in the document?

Could I download the image using AJAX and check its height and width programmatically?

Something like...

var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        var imageSize = MEGIC_GET_FILE_SIZE_FUNCTION(xmlhttp);
        alert("The image is "+imageSize.width+","+imageSize.height+".");
    }
}
xmlhttp.open("GET","lena.jpg",true);
xmlhttp.send();

I'll be using Raphael, so if it offers functionality to this effect, that suits my needs.

like image 629
Richard JP Le Guen Avatar asked Jun 03 '11 17:06

Richard JP Le Guen


1 Answers

You don't need ajax.

var img = new Image();
img.onload = function() {
    alert("The image is " + this.width + "x" + this.height);
}
img.src = "lena.jpg";
like image 83
BalusC Avatar answered Oct 16 '22 07:10

BalusC