How do I get the correct measurements of an image using javascript?

0

My problem is that I want to determine what size minimum and maximum should be the images that will be entered into my web system, both length and height (width and height).

Here is my file-type input

<input type="file" name="file-1[]" id="file-1" class="inputfile inputfile-1" data-multiple-caption="{count} files selected" multiple />

Here is my getting the element file-1 []

var img = document.getElementById('file-1'); 
var width = img.offsetWidth;
var height = img.clientHeight;
    alert(width);

As you can see, I have an alert that results in the following:

    
asked by David 17.08.2016 в 21:10
source

2 answers

0

In this answer published in Stack Overflow in English you can see this code:

<input type="file" id="file" />

var _URL = window.URL || window.webkitURL;

  $("#file").change(function(e) {
    var file, img;
    if ((file = this.files[0])) {
        img = new Image();
        img.onload = function() {
            alert(this.width + " " + this.height);
        };
        img.onerror = function() {
            alert( "not a valid file: " + file.type);
        };
        img.src = _URL.createObjectURL(file);
    }
});

This is the jsfiddle so you can see it working.

    
answered by 17.08.2016 / 21:25
source
0

To be able to obtain the dimensions of the image using javascript, it is necessary to interpret the file as an image, for this we create a new instance of Image and add the event onload to know when the image is ready. You can use a callback to get the results as shown in the following snippet:

var _URL = window.URL || window.webkitURL;

function checkPhoto(target,callback) {
    var file, img;

    file = target.files[0];

    if (file) {
        img = new Image();

        img.onload = function () {
            callback(this.height, this.width, file.size);
        };

        img.src = _URL.createObjectURL(file);
    } 
}

document.getElementById("photoInput").addEventListener("change",function(){
    checkPhoto(this,function(height,width,filesize){
        console.log(height,width,filesize);
        // Validar, si aplica
    });
},false);

You can see the fiddle running here .

    
answered by 17.08.2016 в 21:40