Determining Image File Size and Dimensions via JavaScript
In this article, we will explore how to determine the file size (in kilobytes) and resolution of an image directly within the browser context using JavaScript. This information can be valuable for displaying it on the webpage or for performing various operations.
Retrieving Pixel Dimensions
To obtain the current pixel size of an image element within the browser, excluding its border and margin, utilize the clientWidth and clientHeight properties.
Retrieving File Size
Getting the size of a server-hosted file can be achieved through an Ajax HEAD HTTP Request. This method retrieves HTTP headers without transferring file content. The Content-Length header provides the file's size in bytes.
Note: This approach is subject to the Same Origin Policy, which restricts requests to the same domain.
Retrieving Original Image Dimensions
To determine the original dimensions of an image, create an HTML Image element dynamically. Set its onload event to access its width and height properties after the image loads.
Code Examples:
Pixel Dimensions:
var img = document.getElementById('imageId'); var width = img.clientWidth; var height = img.clientHeight;
File Size using HEAD Request:
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);
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 Determine Image File Size and Dimensions with JavaScript?. For more information, please follow other related articles on the PHP Chinese website!