Find out which image size was inserted by input file

Asked

Viewed 1,426 times

4

I am creating a system to organize the images of a site, that is, I will store information such as name, extension, size, height, width, ... and I am having difficulties to get the data of height and width

The codes currently are:

jQuery:

$(document).ready(function(){
        $('#file').on('change',function(e){

            var input = e.target;
            var reader = new FileReader();
            reader.onload = function(){
          var dataURL = reader.result;
          $('#img').prop('src',dataURL);
          console.log($('#img'));
        };
        reader.readAsDataURL(input.files[0]);

        var arquivo = input.files[0].name;
            var split = arquivo.split('.');
        var extensao = split[split.length-1];
        var nome = arquivo.replace('.'+extensao,'');
        var tamanho = (input.files[0].size/1024).toFixed(2);
        var altura = 'ainda não descobri';
        var largura = 'ainda não descobri';

        $('#arquivo').html('Arquivo: '+arquivo);
        $('#nome').html('Nome: '+nome);
        $('#extensao').html('Extensão: '+extensao);
        $('#tamanho').html('Tamanho: '+tamanho+' kB');
        $('#altura').html('Altura: '+altura);
        $('#largura').html('Largura: '+largura);
        });
    });

HTML:

<input id="file" type='file' accept='image/*'><br>
<br>
<p id="arquivo"></p>
<p id="nome"></p>
<p id="extensao"></p>
<p id="tamanho"></p>
<p id="altura"></p>
<p id="largura"></p>
<br>
<img id='img'>

I found that by writing console.log($('#img')); onload causes the image information to appear on the console, but when typing $('#img').width(); or $('#img').height(); the result becomes 0. Someone can help me?

  • 1

    try the following var width = $('#img'). naturalWidth; var height = $('#img'). naturalHeight;

  • Gets 'Undefined' using the natural...

  • I believe it works only after loading the image

  • I got it with [0]. It got $('#img')[0]. naturalWidth; and $('#img')[0]. naturalHeight.

  • But it only takes from Monday on...

1 answer

3


After image loading you can get these values through its properties, example:

console.log($(img).prop('height'));
console.log($(img).prop('width'));

$('#teste').load(function(){
  	$("#height").html($(this).prop('height'));
    $("#width").html($(this).prop('width'));
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="imagem">
  <img id="teste" src="http://www.google.hr/images/srpr/logo3w.png" />
</div>
<div id="DadosDaImagem">
  <span id="height"></span>
  <span id="width"></span>
</div>

  • It helped me solve the problem: It looked like this: $('#img'). on('load',Function(){ console.log($(this). prop('height')); console.log($(this). prop('width'); });

Browser other questions tagged

You are not signed in. Login or sign up in order to post.