Home > Web Front-end > JS Tutorial > How to Determine Image File Size and Dimensions with JavaScript?

How to Determine Image File Size and Dimensions with JavaScript?

Mary-Kate Olsen
Release: 2024-11-16 00:40:03
Original
501 people have browsed it

How to Determine Image File Size and Dimensions with JavaScript?

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

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!

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