Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

139
Views
How to retrieve image dimensions after loading using readAsDataURL?

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"/>
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

It needs to be called within the .onload callback.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!