Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

140
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda