Home >Web Front-end >JS Tutorial >How do you determine the size and dimensions of an image in a web browser?
In web development, it is often necessary to retrieve information about images displayed on a web page, such as their file size and resolution. This information can be useful for display purposes or for optimizing page performance.
File Size:
XMLHttpRequest (HEAD Request): This method allows you to retrieve the size of a file hosted on the server without downloading the entire file. The response includes the Content-Length header that specifies the file size in bytes.
var xhr = new XMLHttpRequest(); xhr.open('HEAD', 'img/test.jpg', true); xhr.onload = function() { alert('Size in bytes: ' + xhr.getResponseHeader('Content-Length')); }; xhr.send();
Resolution (in-browser pixel dimensions):
clientWidth/clientHeight: These properties return the pixel width and height of a DOM element, including the content, but excluding the border and margin.
var img = document.getElementById('imageId'); var width = img.clientWidth; var height = img.clientHeight;
Original Dimensions (image size before browser rendering):
Create Image Element Programmatically: Create an image element in the DOM and set its source to the image URL. Once the image loads, you can access its width and height properties to get the original 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 do you determine the size and dimensions of an image in a web browser?. For more information, please follow other related articles on the PHP Chinese website!