Como obter o tamanho da imagem (altura e largura) usando JavaScript?


Respostas:


792

Você pode obter programaticamente a imagem e verificar as dimensões usando Javascript ...

var img = new Image();
img.onload = function() {
  alert(this.width + 'x' + this.height);
}
img.src = 'http://www.google.com/intl/en_ALL/images/logo.gif';

Isso pode ser útil se a imagem não fizer parte da marcação.


4
@ blo0p3r - a imagem não precisa ser carregada no DOM antes disso. Carrega a imagem e dispara a carga para nos dar as dimensões. By the way - Melhor resposta aqui !!
— Vik

Eu gostaria que você pudesse fazer isso com um objeto XMLHttpRequest também.
— PHearst

Como posso usar esse código para várias (uma matriz de) imagens? Provavelmente precisaria combiná-lo com a melhor resposta daqui: stackoverflow.com/questions/4288759/… ?
— Kozuch

Solução para várias imagens aqui: stackoverflow.com/questions/19269834/…
— Kozuch 9/10

2
img.onerror = function () {alert (0); // manipulador não encontrado}
— Isit ilimitado

437

clientWidth e clientHeight são propriedades DOM que mostram o tamanho atual no navegador das dimensões internas de um elemento DOM (excluindo margem e borda). Portanto, no caso de um elemento IMG, isso obterá as dimensões reais da imagem visível.

var img = document.getElementById('imageid'); 
//or however you get a handle to the IMG
var width = img.clientWidth;
var height = img.clientHeight;

33
@ Nicky exatamente certo. Ele fornece as dimensões da imagem conforme é renderizada nessa instância .
— Rex M

8
@ Mat-visual $.fn.widthe $.fn.height.
— usar o seguinte comando

202
A resposta correta é usar img.naturalWidth e img.naturalHeight
— Octopus

5
document.getElementByIdé mais longo para digitar, mas 10 vezes mais rápido que $('#...')[0].
— precisa saber é o seguinte

17
@RexM No Chrome 35, é 16 vezes mais rápido: jsperf.com/document-getelementbyid-vs-jquery/5
— bfontaine

335

Além disso (além das respostas de Rex e Ian), há:

imageElement.naturalHeight

e

imageElement.naturalWidth

Eles fornecem a altura e a largura do próprio arquivo de imagem (e não apenas o elemento da imagem).


15
Agora isso é suportado no IE9 e em todos os navegadores modernos.
— Aaron

obtenha 0x0 quando a imagem não terminar de carregar.
— Br17

1
Estou usando o chrome e isso só funciona se o tamanho da imagem no dom não mudar depois que a página for carregada.
— Jonathan Czitkovics

Sim ... é isso que eu faço. E depois, se "largura natural" ou altura voltarem como NaNs, eu reverto para o outro método da resposta anterior (obtenha a imagem novamente como uma nova Imagem () e, em seguida, obtenha sua largura e altura durante o evento onload. mais lento, mas desta forma ele vai trabalhar em navegadores mais antigos como o IE8.
— Randy

no caso de você querer saber sobre o suporte ao navegador caniuse.com/#feat=img-naturalwidth-naturalheight
— Ulmer-Morozov

109

Se você estiver usando o jQuery e solicitando tamanhos de imagem, terá que esperar até que eles sejam carregados ou você receberá apenas zeros.

$(document).ready(function() {
    $("img").load(function() {
        alert($(this).height());
        alert($(this).width());
    });
});

A largura e a altura estão sempre disponíveis no manipulador de carga?
— Anders Lindén

@ AndersLindén - veja a tinta que Akseli adicionou para o evento load. Há uma seção específica dedicada às imagens. A resposta técnica é "não", mas, na prática, nunca tive problemas com nossos sites que usam esse método.
— mrtsherman

Mas se a resposta técnica for não, é inutilizável? Não é?
— Anders Lindén

É possível obter os atributos da imagem antes de carregar?
— no nein

98

Eu acho que uma atualização para essas respostas é útil porque uma das respostas mais votadas sugere o uso de clientWidth clientHeight, que agora acho obsoleto.

Fiz algumas experiências com o HTML5, para ver quais valores realmente são retornados.

Antes de tudo, usei um programa chamado Dash para obter uma visão geral da API da imagem. Ele afirma que heighte widthsão a altura / largura renderizada da imagem e que naturalHeightenaturalWidth são a altura / largura intrínseca da imagem (e são apenas HTML5).

Usei uma imagem de uma linda borboleta, de um arquivo com altura 300 e largura 400. E esse Javascript:

var img = document.getElementById("img1");

console.log(img.height,           img.width);
console.log(img.naturalHeight,    img.naturalWidth);
console.log($("#img1").height(),  $("#img1").width());

Então eu usei esse HTML, com CSS embutido para altura e largura.

<img style="height:120px;width:150px;" id="img1" src="img/Butterfly.jpg" />

Resultados:

/*Image Element*/ height == 300         width == 400
           naturalHeight == 300  naturalWidth == 400
/*Jquery*/      height() == 120       width() == 150

/*Actual Rendered size*/    120                  150

Alterei o HTML para o seguinte:

<img height="90" width="115" id="img1" src="img/Butterfly.jpg" />

ou seja, usando atributos de altura e largura em vez de estilos embutidos

Resultados:

/*Image Element*/ height ==  90         width == 115
           naturalHeight == 300  naturalWidth == 400
/*Jquery*/      height() ==  90       width() == 115

/*Actual Rendered size*/     90                  115

Alterei o HTML para o seguinte:

<img height="90" width="115" style="height:120px;width:150px;" id="img1" src="img/Butterfly.jpg" />

ou seja, usando atributos e CSS, para ver o que tem precedência.

Resultados:

/*Image Element*/ height ==  90         width == 115
           naturalHeight == 300  naturalWidth == 400
/*Jquery*/      height() == 120       width() == 150

/*Actual Rendered size*/    120                  150

1
Por que você acha que clientHeight é obsoleto?
— Cactux

64

Usando o JQuery, você faz isso:

var imgWidth = $("#imgIDWhatever").width();

63
E se a imagem ainda não foi carregada?
— James Westgate

11
e se a imagem estiver na propriedade background da div? :)
— NDM

3
@ JamesWestgate Se a imagem ainda não foi carregada, não há como determinar seu tamanho real. No entanto, você pode tentar ler os atributos widthe heightdo imgelemento.
— Tim

@ Tim Você pode carregá-lo em segundo plano e quando o seu carregado você pode ter as suas dimensões
— Odys

26

O que todos os outros esqueceram é que você não pode verificar o tamanho da imagem antes de carregá-la. Quando o autor verifica todos os métodos publicados, provavelmente funcionará apenas no host local. Como o jQuery pode ser usado aqui, lembre-se de que o evento 'ready' é acionado antes do carregamento das imagens. $ ('# xxx'). width () e .height () devem ser disparados no evento onload ou posterior.


9
Publique um código atualizado, você poderá ser votado e até receber um emblema de reversão cobiçado!
— James Westgate

1
@ Pensador, pls fornece sua solução porque sua análise parece correta.
— a20

5
Esta não é uma resposta. Apenas um comentário sobre as outras respostas.
— precisa saber é o seguinte

20

Você realmente pode fazer isso usando um retorno de chamada do evento load, pois o tamanho da imagem não é conhecido até que o carregamento seja realmente concluído. Algo como o código abaixo ...

var imgTesting = new Image();

function CreateDelegate(contextObject, delegateMethod)
{
    return function()
    {
        return delegateMethod.apply(contextObject, arguments);
    }
}

function imgTesting_onload()
{
    alert(this.width + " by " + this.height);
}


imgTesting.onload = CreateDelegate(imgTesting, imgTesting_onload);
imgTesting.src = 'yourimage.jpg';

1
no jquery, você pode usar $ .proxy para isso.
— Jochem Van Der Spek

9

Com jQuery biblioteca-

Use .width()e .height().

Mais em largura jQuery e altura jQuery .

Código de exemplo

$(document).ready(function(){
    $("button").click(function()
    {
        alert("Width of image: " + $("#img_exmpl").width());
        alert("Height of image: " + $("#img_exmpl").height());
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>

<img id="img_exmpl" src="http://images.all-free-download.com/images/graphicthumb/beauty_of_nature_9_210287.jpg">
<button>Display dimensions of img</button>


8

ok pessoal, acho que aprimorei o código-fonte para poder deixar a imagem carregar antes de tentar descobrir suas propriedades, caso contrário, ele exibirá '0 * 0', porque a próxima instrução teria sido chamada antes do carregamento do arquivo o navegador. Requer jquery ...

function getImgSize(imgSrc){
    var newImg = new Image();
    newImg.src = imgSrc;
    var height = newImg.height;
    var width = newImg.width;
    p = $(newImg).ready(function(){
        return {width: newImg.width, height: newImg.height};
    });
    alert (p[0]['width']+" "+p[0]['height']);
}

8

Supondo que queremos obter as dimensões da imagem de <img id="an-img" src"...">

// Query after all the elements on the page have loaded.
// Or, use `onload` on a particular element to check if it is loaded.
document.addEventListener('DOMContentLoaded', function () {
  var el = document.getElementById("an-img");

  console.log({
    "naturalWidth": el.naturalWidth, // Only on HTMLImageElement
    "naturalHeight": el.naturalHeight, // Only on HTMLImageElement
    "offsetWidth": el.offsetWidth,
    "offsetHeight": el.offsetHeight
  });

Dimensões naturais

el.naturalWidthe el.naturalHeightnos dará as dimensões naturais , as dimensões do arquivo de imagem.

Dimensões do layout

el.offsetWidthe el.offsetHeightobterá as dimensões nas quais o elemento é renderizado no documento.


4
Basta votar nas respostas existentes que fornecem conteúdo útil; não copie de vários deles para um novo; você está apenas duplicando o conteúdo.
— TylerH

7

Antes de usar o tamanho real da imagem, você deve carregar a imagem de origem. Se você usa a estrutura JQuery, pode obter o tamanho real da imagem de maneira simples.

$("ImageID").load(function(){
  console.log($(this).width() + "x" + $(this).height())
})

7

Esta resposta foi exatamente o que eu estava procurando (no jQuery):

var imageNaturalWidth = $('image-selector').prop('naturalWidth');
var imageNaturalHeight = $('image-selector').prop('naturalHeight');

5

Você pode ter uma função simples como a seguinte ( imageDimensions()) se não tem medo de usar promessas .

// helper to get dimensions of an image
const imageDimensions = file => new Promise((resolve, reject) => {
    const img = new Image()

    // the following handler will fire after the successful parsing of the image
    img.onload = () => {
        const { naturalWidth: width, naturalHeight: height } = img
        resolve({ width, height })
    }

    // and this handler will fire if there was an error with the image (like if it's not really an image or a corrupted one)
    img.onerror = () => {
        reject('There was some problem with the image.')
    }
    
    img.src = URL.createObjectURL(file)
})

// here's how to use the helper
const getInfo = async ({ target: { files } }) => {
    const [file] = files
 
    try {
        const dimensions = await imageDimensions(file)
        console.info(dimensions)
    } catch(error) {
        console.error(error)
    }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/7.0.0-beta.3/babel.min.js"></script>

Select an image:
<input
  type="file"
  onchange="getInfo(event)"
/>
<br />
<small>It works offline.</small>


3

Resposta JQuery:

$height = $('#image_id').height();
$width  = $('#image_id').width();

3

Achei que isso poderia ser útil para alguns que estão usando Javascript e / ou texto datilografado em 2019.

Achei o seguinte, como alguns sugeriram, incorreto:

let img = new Image();
img.onload = function() {
  console.log(this.width, this.height) // Error: undefined is not an object
};
img.src = "http://example.com/myimage.jpg";

Isto está correto:

let img = new Image();
img.onload = function() {
  console.log(img.width, img.height)
};
img.src = "http://example.com/myimage.jpg";

Conclusão:

Use img, não this, em onloadfunção.


O img.src acima tem um erro de digitação, deve ser "não: tentei editar isso, mas não posso porque:" As edições devem ter pelo menos 6 caracteres; existe algo mais para melhorar neste post? "Caso contrário, uma solução muito simples que funcione perfeitamente!
— user2677034 03/04

Obrigado @ user2677034 por perceber. Eu não vi isso. Eu culpo o teclado da Apple. Brincadeirinha ... Provavelmente foi minha culpa. ; P
— Brian

2

Recentemente, tive o mesmo problema por um erro no controle deslizante flexível. A altura da primeira imagem foi ajustada menor devido ao atraso no carregamento. Tentei o seguinte método para resolver esse problema e ele funcionou.

// create image with a reference id. Id shall be used for removing it from the dom later.
var tempImg = $('<img id="testImage" />');
//If you want to get the height with respect to any specific width you set.
//I used window width here.
tempImg.css('width', window.innerWidth);  
tempImg[0].onload = function () {
    $(this).css('height', 'auto').css('display', 'none');
    var imgHeight = $(this).height();
    // Remove it if you don't want this image anymore.
    $('#testImage').remove();
}
//append to body
$('body').append(tempImg);
//Set an image url. I am using an image which I got from google.
tempImg[0].src ='http://aspo.org/wp-content/uploads/strips.jpg';

Isso fornecerá a altura em relação à largura definida em vez da largura original ou Zero.


1

Você também pode usar:

var image=document.getElementById("imageID");
var width=image.offsetWidth;
var height=image.offsetHeight;

1

Nicky De Maeyer perguntou após uma imagem de fundo; Eu simplesmente o pego no css e substituo o "url ()":

var div = $('#my-bg-div');
var url = div.css('background-image').replace(/^url\(\'?(.*)\'?\)$/, '$1');
var img = new Image();
img.src = url;
console.log('img:', img.width + 'x' + img.height); // zero, image not yet loaded
console.log('div:', div.width() + 'x' + div.height());
img.onload = function() {
  console.log('img:', img.width + 'x' + img.height, (img.width/div.width()));
}

Eu nunca entendi o uso do regexp para isso ao usar o jQuery. Desde jQuery irá normalizar o atributo para você que você se afastar muito bem usando s.substr(4,s.length-5), é, pelo menos, mais fácil sobre os olhos;)
— Jonas Schubert Erlandsson

1

Você pode aplicar a propriedade onload handler quando a página carregar em js ou jquery desta forma: -

$(document).ready(function(){
   var width = img.clientWidth;
   var height = img.clientHeight;

 });

1

Simplesmente, você pode testar assim.

  <script>
  (function($) {
        $(document).ready(function() {
            console.log("ready....");
            var i = 0;
            var img;
            for(i=1; i<13; i++) {
                img = new Image();
                img.src = 'img/' + i + '.jpg';
                console.log("name : " + img.src);
                img.onload = function() {
                    if(this.height > this.width) {
                        console.log(this.src + " : portrait");
                    }
                    else if(this.width > this.height) {
                        console.log(this.src + " : landscape");
                    }
                    else {
                        console.log(this.src + " : square");
                    }
                }
            }
        });
    }(jQuery));
  </script>

0
var img = document.getElementById("img_id");
alert( img.height + " ;; " + img .width + " ;; " + img .naturalHeight + " ;; " + img .clientHeight + " ;; " + img.offsetHeight + " ;; " + img.scrollHeight + " ;; " + img.clientWidth + " ;; " + img.offsetWidth + " ;; " + img.scrollWidth )
//But all invalid in Baidu browser  360 browser ...

0

é importante remover a configuração interpretada pelo navegador da div pai. Então, se você quiser a largura e a altura reais da imagem, basta usar

$('.right-sidebar').find('img').each(function(){
    $(this).removeAttr("width");
    $(this).removeAttr("height");
    $(this).imageResize();
});

Este é um exemplo do projeto TYPO3, onde preciso das propriedades reais da imagem para dimensioná-la com a relação correta.


0
var imgSrc, imgW, imgH;
function myFunction(image){
    var img = new Image();
    img.src = image;
    img.onload = function() {   
        return {
            src:image,
            width:this.width,
            height:this.height};
        }
    return img;
}
var x = myFunction('http://www.google.com/intl/en_ALL/images/logo.gif');
    //Waiting for the image loaded. Otherwise, system returned 0 as both width and height.
x.addEventListener('load',function(){
    imgSrc = x.src;
    imgW = x.width;
    imgH = x.height;
});
x.addEventListener('load',function(){
    console.log(imgW+'x'+imgH);//276x110
});
console.log(imgW);//undefined.
console.log(imgH);//undefined.
console.log(imgSrc);//undefined.

Este é o meu método, espero que seja útil. :)


0
function outmeInside() {
var output = document.getElementById('preview_product_image');

 if (this.height < 600 || this.width < 600) {
     output.src = "http://localhost/danieladenew/uploads/no-photo.jpg";
     alert("The image you have selected is low resloution image.Your image width=" + this.width + ",Heigh=" + this.height + ". Please select image greater or equal to 600x600,Thanks!");
 } else {
     output.src = URL.createObjectURL(event.target.files[0]);

 }
 return;

 }

 img.src = URL.createObjectURL(event.target.files[0]);
}

este trabalho para visualização e upload de várias imagens. se você precisar selecionar para cada uma das imagens uma a uma. Em seguida, copie e cole em toda a função de visualização da imagem e valide !!!


0

Antes de adquirir os atributos do elemento, a página do documento deve estar onload:

window.onload=function(){
    console.log(img.offsetWidth,img.offsetHeight);
}

0

basta passar o objeto img que é obtido pelo elemento input quando selecionamos o arquivo correto, ele fornecerá a altura e a largura netural da imagem

function getNeturalHeightWidth(file) {
     let h, w;
     let reader = new FileReader();
      reader.onload = () => {
        let tmpImgNode = document.createElement("img");
        tmpImgNode.onload = function() {
          h = this.naturalHeight;
          w = this.naturalWidth;
        };
        tmpImgNode.src = reader.result;
      };
      reader.readAsDataURL(file);
    }
   return h, w;
}
Ao utilizar nosso site, você reconhece que leu e compreendeu nossa Política de Cookies e nossa Política de Privacidade.
Licensed under cc by-sa 3.0 with attribution required.