Determining Image File Size and Dimensions with Javascript
In web applications, it becomes necessary to retrieve information about images displayed on web pages. One common requirement is to determine an image's file size and resolution entirely within the browser context. This article explores various cross-browser techniques to accomplish this task.
Getting Image Dimensions
To determine the resolution of an image displayed on the web page, you can utilize the clientWidth and clientHeight properties of the DOM element containing the image. This approach returns the pixel dimensions of the image within the browser, excluding any borders or margins.
var img = document.getElementById('imageId'); var width = img.clientWidth; var height = img.clientHeight;
Retrieving File Size
To obtain the file size of an image, one option is to use the fileSize property available in Internet Explorer for document and IMG elements. However, this approach is limited to IE and not supported in other browsers.
Using HEAD HTTP Requests
A more versatile technique is to issue an HTTP HEAD request to the image's URL. HEAD requests retrieve metadata about a resource without downloading its contents. The response headers include the Content-Length, representing 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);
Note: Ajax requests are subject to the same-origin policy, meaning they can only access resources from the same domain as the web page.
Retrieving Original Image Dimensions
To determine the original dimensions of an image before resizing or cropping, you can create an IMG element programmatically and set its onload event to retrieve its 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 can I determine the file size and dimensions of an image using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!