Determining Image File Size + Dimensions via JavaScript

Determining image file size + dimensions via Javascript?

Edit:

To get the current in-browser pixel size of a DOM element (in your case IMG elements) excluding the border and margin, you can use the clientWidth and clientHeight properties.

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

var width = img.clientWidth;
var height = img.clientHeight;

Now to get the file size, now I can only think about the fileSize property that Internet Explorer exposes for document and IMG elements...

Edit 2: Something comes to my mind...

To get the size of a file hosted on the server, you could simply make an HEAD HTTP Request using Ajax. This kind of request is used to obtain metainformation about the url implied by the request without transferring any content of it in the response.

At the end of the HTTP Request, we have access to the response HTTP Headers, including the Content-Length which represents the size of the file in bytes.

A basic example using raw XHR:

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

Note: Keep in mind that when you do Ajax requests, you are restricted by the Same origin policy, which allows you to make requests only within the same domain.

Check a working proof of concept here.

Edit 3:

1.) About the Content-Length, I think that a size mismatch could happen for example if the server response is gzipped, you can do some tests to see if this happens on your server.

2.) For get the original dimensions of a image, you could create an IMG element programmatically, for example:

var img = document.createElement('img');

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

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

How do you get the file size of an image on the web page with Javascript?

You can't directly get the file size (or any data from it).

The only way is a bit dirty, because you have to do a XMLHTTPRequest (and it probably won't work with externals images, according to the "Cross Origin Resource Sharing"). But with the browser's cache, it should not cause another HTTP request.

var xhr = new XMLHttpRequest();
xhr.open("GET", "foo.png", true);
xhr.responseType = "arraybuffer";
xhr.onreadystatechange = function() {
if(this.readyState == this.DONE) {
alert("Image size = " + this.response.byteLength + " bytes.");
}
};
xhr.send(null);

How to get image size from a path in javascript?

You can use fetch to get the reponse size. Since you make a request with an image path, the response size will points to the image size.

fetch($('img').prop('src')).then(function (response) {    console.log('size:', response.headers.get("content-length"));});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img src="https://images.unsplash.com/photo-1474511320723-9a56873867b5?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&w=1000&q=80" class="image" width="100PX" height="100PX" width="150" height="100">

How can you determine the file size in JavaScript?

Short answer, you cannot

Also, Check on jGuru How can you check the file size from JavaScript in a form with an input type of file?

You will find some important points

Well the answer is very simple, you cannot.

Reason: The browser security does not allow the scripts
(Javascript/VBScript) or even applets and ActiveX Controls to read
files from the local hard disk. You can only read files if your code
is signed by some Certificate Authority (CA). Now the input type
"FILE" also does not have the permission to read files. We cannot do
anything about that since thats what HTML says. So since it cannot
read files, it cannot find the size of the file with which the input
tag is associated. Since it cannot find the file size, there is no
function exposed by JavaScript/VBScript to return the file size. But
if you need to find the file size, say in order to restrict the size
of the file uploaded to your web-server. Then you can do so by
counting the file contents on the server-side, once the user submits
it to the server. Thats what many of the free e-mail providers like
www.hotmail.com do.

How to get image size in bytes using javascript

If javascript engine supports canvas elements you can try to use canvas element and getImageData to fetch the pixel data from your image. Then, depending on type of the image you could create the binary representation of this image.

Here is info about canvas element and getImagedata api:

http://www.whatwg.org/specs/web-apps/current-work/#dom-context-2d-getimagedata

How do I determine size and format of image dropped onto html page

get the droped file using dataTransfer.items.getAsFile(), you can get file name, type and lastmodified, then use the file to create Image object , there you can get width and height of image.

function allowDrop(event) {  event.preventDefault();}function drop(event) {  event.preventDefault();  var _URL = window.URL || window.webkitURL;  var data = event.dataTransfer.items[0].getAsFile();  var imgType;     var img = new Image();  if(data){   imgType = data.type.split('/').pop().toUpperCase();   img.src = _URL.createObjectURL(data);  }  else {   img.src = event.dataTransfer.getData("Text");   imgType = img.src.split('.').pop();   }    img.onload = function() {    document.getElementById('result').innerHTML = img.width + '*' + img.height + ' ' + (imgType || 'JPG');  }}
.droptarget {  width: 150px;   height: 150px;  border: 1px solid #aaaaaa;  line-height:150px;  text-align: center;}
<div class="droptarget" ondrop="drop(event)" ondragover="allowDrop(event)">Drop Here</div>
<p id="result"></p>


Related Topics



Leave a reply



Submit