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

How to Get Image File Size and Dimensions Using JavaScript?

Barbara Streisand
Release: 2024-11-09 20:57:02
Original
1062 people have browsed it

How to Get Image File Size and Dimensions Using JavaScript?

Determining File Size and Dimensions of Images via JavaScript

Question:

How can you determine the file size (in KB) and resolution of an image rendered on a web page using only JavaScript in a cross-browser compatible manner?

Answer:

Getting Pixel Dimensions:

To retrieve the current in-browser pixel size of an image element, excluding borders and margins, use the following JavaScript:

var img = document.getElementById('imageId'); 

var width = img.clientWidth;
var height = img.clientHeight;
Copy after login

Retrieving File Size:

  • Option 1: HEAD HTTP Request (Recommended)

Make a HEAD request to the server hosting the image using XMLHttpRequest. The Content-Length header in the HTTP response contains 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);
Copy after login
  • Option 2: Element File Size Property (IE Only)

This method is only applicable in Internet Explorer:

var img = document.getElementById('imageId');
var fileSize = img.fileSize;
Copy after login

Getting Original Image Dimensions:

Create an IMG element programmatically and use its onload event to retrieve the 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 Get Image File Size and Dimensions Using 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