Home > Enterprise >  How to retrieve image dimensions after loading using readAsDataURL?
How to retrieve image dimensions after loading using readAsDataURL?

Time:10-07

I am trying to create a very simple image preview function that allows users to choose a local image file and display it on the client browser. Then, I want to retrieve and show the image dimension (height, width) which I am unable to do so.

Attempt #1 After calling readAsDataURL, I attempted to retrieve the image's dimensions immediately - but I failed as the image does not seem to render on the screen before I could read the dimensions.

Attempt #2 Hence, I tried using Promises to make the sequence of function calls synchronous. I was hoping to read the image dimensions after it is rendered on screen. Unfortunately, it is still unsuccessful.

Any help will be appreciated. You can literally copy and paste the code below into an HTML file and see it work. Thanks.

<script>
  var loadFile = function(event) {
    var promise = fileReader(event.target.files[0]);
    promise.then(
        () => {
            var userUploadedImage = document.getElementById('userUploadedImage');
            console.log('Image width:'   userUploadedImage.width); // problem: always appearing 0
            console.log('Image height:'   userUploadedImage.height); // problem: appearing 0
        }
    );
  };
  
  function fileReader(file){
      return new Promise((resolve, reject) => {
        var reader = new FileReader();  
        reader.onload = function(){
          var userUploadedImage = document.getElementById('userUploadedImage');
          userUploadedImage.src = reader.result;
        };
        reader.onerror = reject;
        reader.readAsDataURL(file);
        resolve();
      });
    }
</script>

<input type="file" accept="image/*" onchange="loadFile(event)">
<img id="userUploadedImage"/>

CodePudding user response:

You are calling resolve too early, without waiting for the image to load.

It needs to be called within the .onload callback.

  • Related