0

I need to get image original width for which I'm going to change src attribute, this way:

<input hidden type="file" id="loader" accept="image/*">

$('#m1new').click(function(){
    $('#loader').click();
});

$('#loader').change(function(){
var a = this.files[0];
var reader = new FileReader();
reader.onload = function(e) {
    var src = e.target.result;
    $('#imgt').attr("src", src);
    }
reader.readAsDataURL(a);
var a = $('#imgt').width();
console.log(a);
});

Console says - undefined.

qadenza
  • 9,025
  • 18
  • 73
  • 126

2 Answers2

2

try this:

$('#loader').change(function(){
    var a = this.files[0];
    var reader = new FileReader();
     reader.onload = function(e) {

     var img = new Image();        
     img.onload = function() {
        console.log('width is: '+ img.width);             
     }; 
     img.src = reader.result; 
     }
   reader.readAsDataURL(a);       
});
Umesh Sehta
  • 10,555
  • 5
  • 39
  • 68
2

Console says - undefined.

That console.log should be inside the onload, after setting src, and after a load event on the image:

$('#loader').change(function() {
    var a = this.files[0];
    var reader = new FileReader();
    reader.onload = function(e) {
        var src = e.target.result;
        $('#imgt').on("load", function() { // Hook `load` first
            var a = $(this).width();       // Get the width once loaded
            console.log(a);
        }).attr("src", src);               // Set src AFTER hooking `load`
    }
    reader.readAsDataURL(a);
});

In a comment you've said:

this gives me computed width - 960px - instead of original width - 540px - in this case.

The only reason it would do that is if you have CSS applied to the element. If you do, you didn't mention it in your question. (That was kind of important information. )

You can get the original width from an img element not in the DOM (and thus not subject to CSS):

$('#loader').change(function() {
    var a = this.files[0];
    var reader = new FileReader();
    reader.onload = function(e) {
        var src = e.target.result;
        var img = $("<img>");
        img.on("load", function() {     // Hook `load` first
            var a = $(this).width();    // Get the width once loaded
            console.log(a);
            $("#imgt")[0].src = src;    // Now set it on the image in the DOM
        }).attr("src", src);            // Set src AFTER hooking `load`
    }
    reader.readAsDataURL(a);
});
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875