¿Cómo obtener el tamaño de la imagen (alto y ancho) usando JavaScript?


¿Hay alguna API o método jQuery o JS puro para obtener las dimensiones de una imagen en la página?

Author: Karol Selak, 2009-03-08

23 answers

ClientWidth y clientHeight son propiedades DOM que muestran el tamaño actual en el navegador de las dimensiones internas de un elemento DOM (excluyendo margen y borde). Así que en el caso de un elemento IMG, esto obtendrá las dimensiones reales de la imagen visible.

var img = document.getElementById('imageid'); 
//or however you get a handle to the IMG
var width = img.clientWidth;
var height = img.clientHeight;
 393
Author: Rex M,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-08-21 07:22:53

Puede obtener la imagen mediante programación y comprobar las dimensiones 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';

Esto puede ser útil si la imagen no forma parte del marcado.

 693
Author: Josh Stodola,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-01-18 12:13:38

También (además de las respuestas de Rex e Ian) hay:

imageElement.naturalHeight

Y

imageElement.naturalWidth

Estos proporcionan la altura y el ancho del archivo de imagen en sí (en lugar de solo el elemento de imagen).

 259
Author: olliej,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-08 23:12:05

Si está utilizando jQuery y está solicitando tamaños de imagen, debe esperar hasta que se carguen o solo obtendrá ceros.

$(document).ready(function() {
    $("img").load(function() {
        alert($(this).height());
        alert($(this).width());
    });
});
 106
Author: mrtsherman,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-03-01 21:38:20

Creo que una actualización de estas respuestas es útil porque una de las respuestas mejor votadas sugiere usar clientWidth y clientHeight, que creo que ahora está obsoleta.

He hecho algunos experimentos con HTML5, para ver qué valores realmente se devuelven.

En primer lugar, utilicé un programa llamado Dash para obtener una visión general de la API de imágenes. Establece que height y width son la altura/anchura renderizada de la imagen y que naturalHeight y naturalWidth son la altura/anchura intrínseca de la imagen (y son HTML5 solamente).

Usé una imagen de una hermosa mariposa, de un archivo con altura 300 y ancho 400. Y este Javascript:

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

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

Luego usé este HTML, con CSS en línea para la altura y el ancho.

<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

Luego cambié el HTML a lo siguiente:

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

Es decir, usar atributos de altura y anchura en lugar de estilos en línea

Resultados:

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

/*Actual Rendered size*/     90                  115

Luego cambié el HTML a la siguiente:

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

Es decir, usando ambos atributos y CSS, para ver cuál tiene prioridad.

Resultados:

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

/*Actual Rendered size*/    120                  150
 89
Author: paulo62,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-08 22:45:35

Usando jQuery puedes hacer esto:

var imgWidth = $("#imgIDWhatever").width();
 62
Author: Ian Suttle,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-03-08 06:59:57

Lo que todos los demás han olvidado es que no puede comprobar el tamaño de la imagen antes de que se cargue. Cuando el autor comprueba todos los métodos publicados, probablemente solo funcionará en localhost. Dado que jQuery se puede usar aquí, recuerde que el evento 'ready' se dispara antes de que se carguen las imágenes. $('#xxx').width() y .height () debe dispararse en el evento onload o posterior.

 26
Author: Thinker,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-03-10 13:54:42

Solo puede hacer esto usando una devolución de llamada del evento load ya que el tamaño de la imagen no se conoce hasta que haya terminado de cargarse. Algo así como el código de abajo...

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';
 18
Author: Lee Hesselden,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-08-04 11:50:29

Con jQuery biblioteca -

Utilizar .width() y .height().

Más en Ancho de jQuery y altura de jQuery.

Código de ejemplo -

$(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
Author: Abrar Jahin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-30 04:53:46

Ok chicos, creo que mejoré el código fuente para poder dejar que la imagen se cargue antes de intentar averiguar sus propiedades, de lo contrario mostrará '0 * 0', porque la siguiente instrucción se habría llamado antes de que el archivo se cargara en el navegador. Requiere 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']);
}
 7
Author: claudio,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-03-01 21:41:00

Antes de usar el tamaño de imagen real, debe cargar la imagen de origen. Si utiliza jQuery framework puede obtener tamaño de imagen real de manera sencilla.

$("ImageID").load(function(){
  console.log($(this).width() + "x" + $(this).height())
})
 6
Author: sub,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-12-19 13:41:53

Esta respuesta era exactamente lo que estaba buscando (en jQuery):

var imageNaturalWidth = $('image-selector').prop('naturalWidth');
var imageNaturalHeight = $('image-selector').prop('naturalHeight');
 4
Author: dev101,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:26:35

Respuesta de jQuery:

$height = $('#image_id').height();
$width  = $('#image_id').width();
 2
Author: Eli Geske,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-01-02 07:16:44

Simplemente, puedes probar así.

  <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>
 2
Author: cloudrain21,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-26 02:31:45

También puedes usar:

var image=document.getElementById("imageID");
var width=image.offsetWidth;
var height=image.offsetHeight;
 1
Author: praveenjayapal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-02-18 01:05:41

Nicky De Maeyer preguntó por una imagen de fondo; simplemente la obtengo del css y reemplazo la"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()));
}
 1
Author: Hraban,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-04-19 15:09:43
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 ...
 1
Author: user3496915,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-04-04 07:46:30

Recientemente tuve el mismo problema por un error en el control deslizante flex. La altura de la primera imagen se estableció más pequeña debido al retraso de carga. Probé el siguiente método para resolver ese problema y ha funcionado.

// 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';

Esto le dará la altura con respecto al ancho que estableció en lugar del ancho original o Cero.

 1
Author: muhammed basil,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-10-14 14:37:51

Puede aplicar la propiedad onload handler cuando la página se carga en js o jquery de la siguiente manera: -

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

 });
 1
Author: Harkamal Singh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-03-12 09:59:18
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 es mi método, espero que esto sea útil. :)

 1
Author: DHA,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-10-01 13:16:28

Es importante eliminar la configuración interpretada del navegador del div padre. Así que si desea el ancho y alto de la imagen real, puede usar

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

Este es un ejemplo de proyecto TYPO3 mío donde necesito las propiedades reales de la imagen para escalarla con la relación correcta.

 0
Author: Rogoit,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-10-12 09:45:27
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]);
}

Esto funciona para previsualizar y cargar varias imágenes . si tienes que seleccionar para cada una de las imágenes una por una . A continuación, copiar y pasado en toda la función de imagen de vista previa y validar!!!

 0
Author: danielad,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-02-09 15:41:24

Antes de adquirir los atributos del elemento, la página del documento debe ser onload:

window.onload=function(){
    console.log(img.offsetWidth,img.offsetHeight);
}
 0
Author: 中国程序员,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-03 03:28:01