Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

143
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda