Determining Image File Size and Dimensions in Javascript
In a web application, determining an image's file size (in kb) and resolution directly from the browser context is essential for various purposes, such as displaying this information on the page. This article explores solutions to achieve this cross-browser functionality without relying on ActiveX controls or Java applets.
Retrieving Image Dimensions
To obtain the pixel size of an image element within the browser, excluding the border and margin, one can utilize the clientWidth and clientHeight properties:
var img = document.getElementById('imageId'); var width = img.clientWidth; var height = img.clientHeight;
Determining File Size
Unfortunately, browser APIs lack direct support for accessing the file size of an image. However, a workaround involves making an HEAD HTTP request using Ajax:
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);
Note: This method is subject to the same-origin policy, allowing requests only within the same domain.
Extra Considerations
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 Can I Get Image File Size and Dimensions in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!