Getting width & height of an image with filereader

JavascriptDomFilereader

Javascript Problem Overview


I am building an image resize/crop, and I'd like to show a live preview after they've edited it in a modal (bootstrap). This should work, I believe, but I just get 0 in console.log. This requires feeding the width and the height of the original image into another script (which I'll do after, just need them in console.log/a variable for now)

function doProfilePictureChangeEdit(e) {
    var files = document.getElementById('fileupload').files[0];
    var reader = new FileReader();
    reader.onload = (function(theFile) {
        document.getElementById('imgresizepreview').src = theFile.target.result;

        document.getElementById('profilepicturepreview').src = theFile.target.result;
      }
    );
    reader.readAsDataURL(files);
    var imagepreview = document.getElementById('imgresizepreview');
    console.log(imagepreview.offsetWidth);
    $('img#imgresizepreview').imgAreaSelect({
        handles: true,
        enable: true,
        aspectRatio: "1:1",
        onSelectEnd: preview
    });
    $('#resizeprofilepicturemodal').modal('show');
    };

Javascript Solutions


Solution 1 - Javascript

You have to wait for the image to load. Try handling the element inside .onload.

I've also simplified the process of setting the source of the two elements to how you should be doing it (with jQuery).

reader.onload = (function(theFile) { 
    var image = new Image();
    image.src = theFile.target.result;

    image.onload = function() {
        // access image size here 
        console.log(this.width);

        $('#imgresizepreview, #profilepicturepreview').attr('src', this.src);
    };
});

Solution 2 - Javascript

For me the solution of Austin didn't work, so I present the one worked for me:

var reader = new FileReader;

reader.onload = function() {
    var image = new Image();

    image.src = reader.result;

    image.onload = function() {
        alert(image.width);
    };
     
};

reader.readAsDataURL(this.files[0]);

And if you find that assignment image.src = reader.result; takes place after image.onload a bit wired, I think so too.

Solution 3 - Javascript

fileChangeEventHeader(fileInput) {
    const oFReader = new FileReader();
    oFReader.readAsDataURL(fileInput.target.files[0]);
    oFReader.onload = (event: any) => {
      var image = new Image();
      image.src = event.target.result;
      image.onload = function () {
        console.log(`width : ${image.width} px`, `height: ${image.height} px`);
      };
    };
  }

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>

<input type="file" name="profile_img" accept="image/*" (change)="fileChangeEventHeader($event)"
                  class="input-file">

Solution 4 - Javascript

Here's an answer inspired by Austin Brunkhorst with a callback for ascertaining image size in case you want to reuse the function elsewhere in your code.

fileControl is assumed to be a jQuery element.

function didUploadImage(fileControl) {      
   // Render image if file exists.
   var domFileControl = fileControl[0];
   if (domFileControl.files && domFileControl.files[0]) {
      // Get first file.
      var firstFile = domFileControl.files[0];

      // Create reader.
      var reader = new FileReader();

      // Notify parent when image read.
      reader.onload = function(e) {
         // Get image URL.
         var imageURL = reader.result;

      	// Get image size for image.
      	getImageSize(imageURL, function(imageWidth, imageHeight) {
            // Do stuff here.
      	});
      };

      // Read image from hard disk.
      reader.readAsDataURL(firstFile);
      
      // Print status.
      console.log("Uploaded image: " + firstFile.name);
   }
}


function getImageSize(imageURL, callback) {      
   // Create image object to ascertain dimensions.
   var image = new Image();

   // Get image data when loaded.
   image.onload = function() {      
      // No callback? Show error.
      if (!callback) {
         console.log("Error getting image size: no callback. Image URL: " + imageURL);

      // Yes, invoke callback with image size.
      } else {
         callback(this.naturalWidth, this.naturalHeight);
      }
   }

   // Load image.
   image.src = imageURL;
}

Solution 5 - Javascript

this is the way I have for AngularJS

          fileReader.readAsDataUrl($scope.file, $scope).then(function(result) {
               var image = new Image();
               image.src = result;
               image.onload = function() {
                    console.log(this.width);
               };
               $scope.imageSrc = result; //all I wanted was to find the width and height


          });

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMartin AldersonView Question on Stackoverflow
Solution 1 - JavascriptAustin BrunkhorstView Answer on Stackoverflow
Solution 2 - JavascriptandilabsView Answer on Stackoverflow
Solution 3 - JavascriptChandrakesha RaoView Answer on Stackoverflow
Solution 4 - JavascriptCrashalotView Answer on Stackoverflow
Solution 5 - JavascriptBrian SanchezView Answer on Stackoverflow