Determining File Size and Dimensions of Images via JavaScript
Question:
How can you determine the file size (in KB) and resolution of an image rendered on a web page using only JavaScript in a cross-browser compatible manner?
Answer:
Getting Pixel Dimensions:
To retrieve the current in-browser pixel size of an image element, excluding borders and margins, use the following JavaScript:
var img = document.getElementById('imageId'); var width = img.clientWidth; var height = img.clientHeight;
Retrieving File Size:
Make a HEAD request to the server hosting the image using XMLHttpRequest. The Content-Length header in the HTTP response contains the file size in bytes.
var xhr = new XMLHttpRequest(); xhr.open('HEAD', 'img/test.jpg', true); xhr.onreadystatechange = function(){ if ( xhr.readyState == 4 ) { if ( xhr.status == 200 ) { alert('Size in bytes: ' + xhr.getResponseHeader('Content-Length')); } else { alert('ERROR'); } } }; xhr.send(null);
This method is only applicable in Internet Explorer:
var img = document.getElementById('imageId'); var fileSize = img.fileSize;
Getting Original Image Dimensions:
Create an IMG element programmatically and use its onload event to retrieve the original image dimensions:
var img = document.createElement('img'); img.onload = function () { alert(img.width + ' x ' + img.height); }; img.src='http://sstatic.net/so/img/logo.png';
The above is the detailed content of How to Get Image File Size and Dimensions Using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!