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
Barbara StreisandOriginal
2024-11-09 20:57:021077browse

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;

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);
  • 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;

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';

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!

Statement:
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