About size verification

5

I have already found several explanations about, but not conclusive. Is it possible to determine the size (in bytes) of an image after it is loaded and using Javascript? Apparently browser security would prevent us from pulling this information via XMLHttpRequest by giving error in cross domain request, is there a way to overcome this limitation?

    
asked by anonymous 16.07.2014 / 15:57

1 answer

3

Recover image data on local disk:

For browsers that support HTML5 / CSS3, it is possible according to the following code:

HTML:

<input type="file" id="choose" multiple="multiple" />
<br>
<div id="uploadPreview"></div>

Javascript:

// var url = window.URL || window.webkitURL; // alternate use

function readImage(file) {

    var reader = new FileReader();
    var image  = new Image();

    reader.readAsDataURL(file);  
    reader.onload = function(_file) {
        image.src    = _file.target.result;              // url.createObjectURL(file);
        image.onload = function() {
            var w = this.width,
                h = this.height,
                t = file.type,                           // ext only: // file.type.split('/')[1],
                n = file.name,
                s = ~~(file.size/1024) +'KB';
            $('#uploadPreview').append('<img src="'+ this.src +'"> '+w+'x'+h+' '+s+' '+t+' '+n+'<br>');
        };
        image.onerror= function() {
            alert('Invalid file type: '+ file.type);
        };      
    };

}
$("#choose").change(function (e) {
    if(this.disabled) return alert('File upload not supported!');
    var F = this.files;
    if(F && F[0]) for(var i=0; i<F.length; i++) readImage( F[i] );
});

The line s = ~~(file.size/1024) +'KB'; gives the size in bytes.

See this link for a demo.

I used this answer of stackoverflow in English.

Retrieve uploaded image data from a URL:

The following is a simple example that shows properties of an image retrieved from a URL without displaying the size:

var img = new Image();
img.onload = function() {
  alert(this.width + 'x' + this.height);
}
img.src = 'http://www.google.com/intl/en_ALL/images/logo.gif';

This response is also taken from a link of stackoverflow in English.

Secondly, this link of stackoverflow in English, it is not possible to retrieve the size of an image on the page, via javascript, only via server side. See that the answer was marked correct.

    
16.07.2014 / 16:43