Home > Web Front-end > JS Tutorial > body text

How Can I Get Image File Size and Dimensions in JavaScript?

Susan Sarandon
Release: 2024-11-10 10:38:02
Original
212 people have browsed it

How Can I Get Image File Size and Dimensions in JavaScript?

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;
Copy after login

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);
Copy after login

Note: This method is subject to the same-origin policy, allowing requests only within the same domain.

Extra Considerations

  • The Content-Length header value may not accurately reflect the actual image size if the response is compressed (e.g., gzipped).
  • To obtain the original image dimensions without loading the image fully into the document, create an image element programmatically and assign the image source:
var img = document.createElement('img');

img.onload = function () { alert(img.width + ' x ' + img.height); };

img.src='http://sstatic.net/so/img/logo.png';
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template