Obtener el ancho y alto real de una imagen con JavaScript? (en Safari / Chrome)


Estoy creando un plugin jQuery.

¿Cómo obtengo el ancho y el alto de una imagen real con Javascript en Safari?

Lo siguiente funciona con Firefox 3, IE7 y Opera 9:

var pic = $("img")

// need to remove these in of case img-element has set width and height
pic.removeAttr("width"); 
pic.removeAttr("height");

var pic_real_width = pic.width();
var pic_real_height = pic.height();

Pero en los navegadores Webkit como Safari y Google Chrome los valores son 0.

Author: sandstrom, 2008-11-25

30 answers

Los navegadores Webkit establecen las propiedades height y width después de cargar la imagen. En lugar de usar tiempos de espera, recomiendo usar el evento onload de una imagen. He aquí un ejemplo rápido:

var img = $("img")[0]; // Get my img elem
var pic_real_width, pic_real_height;
$("<img/>") // Make in memory copy of image to avoid css issues
    .attr("src", $(img).attr("src"))
    .load(function() {
        pic_real_width = this.width;   // Note: $(this).width() will not
        pic_real_height = this.height; // work for in memory images.
    });

Para evitar cualquiera de los efectos que CSS podría tener en las dimensiones de la imagen, el código anterior hace una copia en memoria de la imagen. Esta es una solución muy inteligente sugerida por FDisk .

También puede usar los atributos naturalHeight y naturalWidth HTML5.

 345
Author: Xavi,
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:10:08

Utilice los atributos naturalHeight y naturalWidthde HTML5.

Por ejemplo:

var h = document.querySelector('img').naturalHeight;

Funciona en IE9+, Chrome, Firefox, Safari y Opera ( estadísticas ).

 274
Author: sandstrom,
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-12-08 13:13:04


function getOriginalWidthOfImg(img_element) {
    var t = new Image();
    t.src = (img_element.getAttribute ? img_element.getAttribute("src") : false) || img_element.src;
    return t.width;
}

No es necesario eliminar el estilo de los atributos image o image dimensions. Simplemente cree un elemento con javascript y obtenga el ancho del objeto creado.

 58
Author: FDisk,
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
2010-07-07 07:00:58

El problema raíz es que los navegadores WebKit (Safari y Chrome) cargan información JavaScript y CSS en paralelo. Por lo tanto, JavaScript puede ejecutarse antes de que se hayan calculado los efectos de estilo de CSS, devolviendo la respuesta incorrecta. En jQuery, he encontrado que la solución es esperar hasta el documento.readyState = = 'complete',.por ejemplo,

jQuery(document).ready(function(){
  if (jQuery.browser.safari && document.readyState != "complete"){
    //console.info('ready...');
    setTimeout( arguments.callee, 100 );
    return;
  } 
  ... (rest of function) 

En cuanto a anchura y altura va... dependiendo de lo que esté haciendo, es posible que desee offsetWidth y offsetHeight, que incluyen cosas como bordes y relleno.

 16
Author: Cugel,
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
2008-11-25 20:47:47

Hay mucha discusión en la respuesta aceptada sobre un problema en el que el evento onload no se dispara si se carga una imagen desde la caché de WebKit.

En mi caso, onload se activa para las imágenes almacenadas en caché, pero la altura y el ancho siguen siendo 0. Un simple setTimeout resolvió el problema para mí:

$("img").one("load", function(){
    var img = this;
    setTimeout(function(){
        // do something based on img.width and/or img.height
    }, 0);
});

No puedo decir por qué el evento onload se está disparando incluso cuando la imagen se carga desde la caché (¿mejora de jQuery 1.4/1.5?)- pero si usted todavía está experimentando este problema, tal vez un la combinación de mi respuesta y la técnica var src = img.src; img.src = ""; img.src = src; funcionará.

(Tenga en cuenta que para mis propósitos, no me preocupan las dimensiones predefinidas, ni en los atributos de la imagen ni en los estilos CSS, pero es posible que desee eliminarlas, según la respuesta de Xavi. O clonar la imagen.)

 16
Author: JKS,
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-02-05 20:00:41

Esto funciona para mí (safari 3.2), disparando desde dentro del evento window.onload:

$(window).load(function() {
  var pic = $('img');

  pic.removeAttr("width"); 
  pic.removeAttr("height");

  alert( pic.width() );
  alert( pic.height() );
});
 11
Author: Owen,
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
2008-11-25 20:16:29

Puede obtener la imagen mediante programación y comprobar las dimensiones usando Javascript sin tener que meterse con el DOM en absoluto.

var img = new Image();
img.onload = function() {
  console.log(this.width + 'x' + this.height);
}
img.src = 'http://www.google.com/intl/en_ALL/images/logo.gif';
 8
Author: Yëco,
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-05-31 21:15:55

Cómo obtenemos las dimensiones reales correctas sin un parpadeo de imagen real:

(function( $ ){
   $.fn.getDimensions=function(){
         alert("First example:This works only for HTML code without CSS width/height definition.");
         w=$(this, 'img')[0].width;
         h=$(this, 'img')[0].height;

         alert("This is a width/height on your monitor: " + $(this, 'img')[0].width+"/"+$(this, 'img')[0].height);

         //This is bad practice - it shows on your monitor
         $(this, 'img')[0].removeAttribute( "width" );
         $(this, 'img')[0].removeAttribute( "height" );
         alert("This is a bad effect of view after attributes removing, but we get right dimensions: "+  $(this, 'img')[0].width+"/"+$(this, 'img')[0].height);
         //I'am going to repare it
         $(this, 'img')[0].width=w;
         $(this, 'img')[0].height=h;
         //This is a good practice - it doesn't show on your monitor
         ku=$(this, 'img').clone(); //We will work with a clone
         ku.attr( "id","mnbv1lk87jhy0utrd" );//Markup clone for a final removing
         ku[0].removeAttribute( "width" );
         ku[0].removeAttribute( "height" );
         //Now we still get 0
         alert("There are still 0 before a clone appending to document: "+ $(ku)[0].width+"/"+$(ku)[0].height);
         //Hide a clone
         ku.css({"visibility" : "hidden",'position':'absolute','left':'-9999px'}); 
         //A clone appending
         $(document.body).append (ku[0]);
         alert("We get right dimensions: "+ $(ku)[0].width+"/"+$(ku)[0].height);
         //Remove a clone
         $("#mnbv1lk87jhy0utrd").remove();

         //But a next resolution is the best of all. It works in case of CSS definition of dimensions as well.
         alert("But if you want to read real dimensions for image with CSS class definition outside of img element, you can't do it with a clone of image. Clone method is working with CSS dimensions, a clone has dimensions as well as in CSS class. That's why you have to work with a new img element.");
         imgcopy=$('<img src="'+ $(this, 'img').attr('src') +'" />');//new object 
         imgcopy.attr( "id","mnbv1lk87jhy0aaa" );//Markup for a final removing
         imgcopy.css({"visibility" : "hidden",'position':'absolute','left':'-9999px'});//hide copy 
         $(document.body).append (imgcopy);//append to document 
         alert("We get right dimensions: "+ imgcopy.width()+"/"+imgcopy.height());
         $("#mnbv1lk87jhy0aaa").remove();


   }
})( jQuery );

$(document).ready(function(){

   $("img.toreaddimensions").click(function(){$(this).getDimensions();});
});

Funciona con

 5
Author: Fox,
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
2010-12-10 14:29:22

¿Y las propiedades image.naturalHeight y image.naturalWidth?

Parece funcionar bien de nuevo un buen número de versiones en Chrome, Safari y Firefox, pero no en absoluto en IE8 o incluso IE9.

 5
Author: Andrew Mackenzie,
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-13 00:08:19

Jquery tiene dos propiedades llamadas naturalWidth y naturalHeight, que puede usar de esta manera.

$('.my-img')[0].naturalWidth 
$('.my-img')[0].naturalHeight

Donde my-img es un nombre de clase usado para seleccionar mi imagen.

 4
Author: Samuel Santos,
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-07-31 13:13:13

Como se indicó anteriormente, Xavi answer no funcionará si las imágenes están en la caché. El problema responde a que webkit no dispara el evento load en imágenes almacenadas en caché, por lo que si los attr de ancho/alto no están establecidos explícitamente en la etiqueta img, la única forma confiable de obtener las imágenes es esperar a que se dispare el evento window.load.

El evento window.load se disparará siempre, por lo que es seguro acceder al ancho/alto de e img después de eso sin ningún truco.

$(window).load(function(){

   //these all work

   $('img#someId').css('width');
   $('img#someId').width();
   $('img#someId').get(0).style.width;
   $('img#someId').get(0).width; 

});

Si necesita obtener el tamaño de las imágenes cargadas dinámicamente que podrían almacenarse en caché (previamente cargadas), puede usar el método Xavi más una cadena de consulta para activar una actualización de caché. La desventaja es que causará otra solicitud al servidor, para un img que ya está almacenado en caché y debería estar disponible. Estúpido Webkit.

var pic_real_width   = 0,
    img_src_no_cache = $('img#someId').attr('src') + '?cache=' + Date.now();

$('<img/>').attr('src', img_src_no_cache).load(function(){

   pic_real_width = this.width;

});

Pd: si ya tienes un QueryString en el img.src, tendrás que analizarlo y añadir el parámetro extra para borrar la caché.

 3
Author: xmarcos,
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 11:55:04

Como dice Luke Smith, la carga de imagen es un desastre. No es confiable en todos los navegadores. Este hecho me ha causado un gran dolor. Una imagen en caché no activará el evento en absoluto en algunos navegadores, por lo que aquellos que dijeron "la carga de la imagen es mejor que setTimeout" están equivocados.

La solución de Luke Smith está aquí.

Y hay una discusión interesante sobre cómo se podría manejar este lío en jQuery 1.4.

He encontrado que es bastante confiable establecer el ancho en 0, a continuación, espere a que la propiedad "complete" sea verdadera y la propiedad width sea mayor que cero. También deberías estar atento a los errores.

 2
Author: Nosredna,
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-11-09 15:49:06
$("#myImg").one("load",function(){
  //do something, like getting image width/height
}).each(function(){
  if(this.complete) $(this).trigger("load");
});

Del comentario de Chris: http://api.jquery.com/load-event /

 2
Author: Jerome Jaglale,
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
2010-07-09 21:39:54

Mi situación es probablemente un poco diferente. Estoy cambiando dinámicamente el src de una imagen a través de javascript y necesitaba asegurarme de que la nueva imagen tenga un tamaño proporcional para ajustarse a un contenedor fijo (en una galería de fotos). Inicialmente solo eliminé los atributos width y height de la imagen después de cargarla (a través del evento load de la imagen) y los restablecí después de calcular las dimensiones preferidas. Sin embargo, eso no funciona en Safari y posiblemente IE (no lo he probado en IE a fondo, pero la imagen ni siquiera se muestra, así que...).

De todos modos, Safari mantiene las dimensiones de la imagen anterior por lo que las dimensiones son siempre una imagen detrás. Supongo que esto tiene algo que ver con el caché. Por lo tanto, la solución más simple es clonar la imagen y agregarla al DOM (es importante que se agregue al DOM para obtener el con y la altura). Dale a la imagen un valor de visibilidad de hidden (no uses display none porque no funcionará). Después de obtener las dimensiones quitar el clon.

Aquí está mi código usando jQuery:

// Hack for Safari and others
// clone the image and add it to the DOM
// to get the actual width and height
// of the newly loaded image

var cloned, 
    o_width, 
    o_height, 
    src = 'my_image.jpg', 
    img = [some existing image object];

$(img)
.load(function()
{
    $(this).removeAttr('height').removeAttr('width');
    cloned = $(this).clone().css({visibility:'hidden'});
    $('body').append(cloned);
    o_width = cloned.get(0).width; // I prefer to use native javascript for this
    o_height = cloned.get(0).height; // I prefer to use native javascript for this
    cloned.remove();
    $(this).attr({width:o_width, height:o_height});
})
.attr(src:src);

Esta solución funciona en cualquier caso.

 2
Author: Duane Comeaux,
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-11-01 01:13:02

Ahora hay un complemento de jQuery, event.special.load, para tratar los casos en los que el evento de carga en una imagen en caché no se dispara: http://github.com/peol/jquery.imgloaded/raw/master/ahpi.imgload.js

 1
Author: Sergio1132,
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
2010-09-24 22:47:53

Recientemente necesitaba encontrar ancho y alto para establecer el tamaño predeterminado de .diálogo que representa el gráfico. La solución que utilizo fue:

 graph= $('<img/>', {"src":'mySRC', id:'graph-img'});
    graph.bind('load', function (){
        wid = graph.attr('width');
        hei = graph.attr('height');

        graph.dialog({ autoOpen: false, title: 'MyGraphTitle', height:hei, width:wid })
    })

Para mí esto funciona en FF3, Opera 10, ES decir, 8,7,6

P.D. Usted puede ser encontrar algunas soluciones más mirando dentro de algunos plugins como LightBox o ColorBox

 1
Author: SDemonUA,
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-01-26 17:30:59

Para añadir a la respuesta de Xavi, Github de Paul Irish Gitgub de David Desandro ofrece una función llamada imagesLoaded() que funciona con los mismos principios, y evita el problema de que algunas imágenes en caché del navegador no disparen el .evento load () (con conmutación clever original_src -> data_uri -> original_src).

Es ampliamente utilizado y actualizado regularmente, lo que contribuye a que sea la solución más robusta al problema, IMO.

 1
Author: RobW,
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-10-04 17:16:48

Esto funciona tanto para las imágenes almacenadas en caché como para las cargadas dinámicamente.

function LoadImage(imgSrc, callback){
  var image = new Image();
  image.src = imgSrc;
  if (image.complete) {
    callback(image);
    image.onload=function(){};
  } else {
    image.onload = function() {
      callback(image);
      // clear onLoad, IE behaves erratically with animated gifs otherwise
      image.onload=function(){};
    }
    image.onerror = function() {
        alert("Could not load image.");
    }
  }
}

Para usar este script:

function AlertImageSize(image) {
  alert("Image size: " + image.width + "x" + image.height);
}
LoadImage("http://example.org/image.png", AlertImageSize);

Demo: http://jsfiddle.net/9543z/2 /

 1
Author: CheeseSucker,
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-20 12:45:48

He hecho alguna función de utilidad de solución alternativa, utilizando imagesLoaded jquery plugin: https://github.com/desandro/imagesloaded

            function waitForImageSize(src, func, ctx){
                if(!ctx)ctx = window;
                var img = new Image();
                img.src = src;
                $(img).imagesLoaded($.proxy(function(){
                    var w = this.img.innerWidth||this.img.naturalWidth;
                    var h = this.img.innerHeight||this.img.naturalHeight;
                    this.func.call(this.ctx, w, h, this.img);
                },{img: img, func: func, ctx: ctx}));
            },

Puede usar esto pasando la url, la función y su contexto. La función se realiza después de que se carga la imagen y devuelve la imagen creada, su ancho y alto.

waitForImageSize("image.png", function(w,h){alert(w+","+h)},this)
 1
Author: Zdeněk Mlčoch,
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 08:10:09

Si la imagen ya está utilizada, debe:

  1. Establecer simensiones de imagen en inicial

    Imagen.css ('ancho', 'inicial'); imagen.css ('height','initial');

  2. Obtener dimensiones

    Var originalWidth = this(this).ancho(); var originalHeight = this (this).altura();

 1
Author: Sebastián Rojas,
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-02-26 05:40:26

Puede utilizar las propiedades naturalWidth y naturalHeight del elemento HTML image. (Aquí hay más info ).

Lo usarías así:

//you need a reference to the DOM element, not a jQuery object. It would be better if you can use document.getElementByTagsName or ID or any other native method
var pic = $("img")[0];
var pic_real_width = pic.naturalWidth;
var pic_real_height = pic.naturalHeight;

Parece que esto funciona en todos los navegadores excepto en IE desde la versión 8 y por debajo.

 1
Author: Jair Reina,
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-12-14 22:43:43

Para funciones donde no desea alterar la ubicación o imagen original.

$(this).clone().removeAttr("width").attr("width");
$(this).clone().removeAttr("height").attr("height);
 0
Author: Davin,
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-27 15:04:39

He comprobado la respuesta de Dio y funciona muy bien para mí.

$('#image').fadeIn(10,function () {var tmpW = $(this).width(); var tmpH = $(this).height(); });

Asegúrese de llamar a todas sus funciones aso. que maneja con el tamaño de la imagen en la función recaller de fadeIn ().

Gracias por esto.

 0
Author: drublic,
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
2010-12-14 09:49:39

Utilizo un enfoque diferente, simplemente hago una llamada Ajax al servidor para obtener el tamaño de la imagen cuando el objeto de imagen está en uso.

//make json call to server to get image size
$.getJSON("http://server/getimagesize.php",
{"src":url},
SetImageWidth
);

//callback function
function SetImageWidth(data) {

    var wrap = $("div#image_gallery #image_wrap");

    //remove height
     wrap.find("img").removeAttr('height');
    //remove height
     wrap.find("img").removeAttr('width');

    //set image width
    if (data.width > 635) {
        wrap.find("img").width(635);
    }
    else {
         wrap.find("img").width(data.width);
    }
}

Y por supuesto código del lado del servidor:

<?php

$image_width = 0;
$image_height = 0;

if (isset ($_REQUEST['src']) && is_file($_SERVER['DOCUMENT_ROOT'] . $_REQUEST['src'])) {

    $imageinfo = getimagesize($_SERVER['DOCUMENT_ROOT'].$_REQUEST['src']);
    if ($imageinfo) {
       $image_width=  $imageinfo[0];
       $image_height= $imageinfo[1];
    }
}

$arr = array ('width'=>$image_width,'height'=>$image_height);

echo json_encode($arr);

?>
 0
Author: damijanc,
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
2010-12-17 10:07:57

Esto funciona cross browser

var img = new Image();
$(img).bind('load error', function(e)
{
    $.data(img, 'dimensions', { 'width': img.width, 'height': img.height });                    
});
img.src = imgs[i];              

Obtenga las dimensiones usando

$(this).data('dimensions').width;
$(this).data('dimensions').height;

Salud!

 0
Author: foxybagga,
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-01-03 05:19:36

Otra sugerencia es utilizar imagesLoaded plugin.

$("img").imagesLoaded(function(){
alert( $(this).width() );
alert( $(this).height() );
});
 0
Author: gadelkareem,
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-05 20:46:23
$(document).ready(function(){
                            var image = $("#fix_img");
                            var w = image.width();
                            var h = image.height();
                            var mr = 274/200;
                            var ir = w/h
                            if(ir > mr){
                                image.height(200);
                                image.width(200*ir);
                            } else{
                                image.width(274);
                                image.height(274/ir);
                            }
                        }); 

// Este código ayuda a mostrar la imagen con 200 * 274 dimension

 0
Author: Eranda,
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-08-03 05:11:25

Aquí hay una solución de navegador cruzado que activa un evento cuando se cargan las imágenes seleccionadas: http://desandro.github.io/imagesloaded / puede buscar la altura y el ancho dentro de la función imagesLoaded ().

 0
Author: Paul Mason,
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-05-01 20:22:12

Me topé con este hilo tratando de encontrar una respuesta para mi propia pregunta. Estaba tratando de obtener el ancho/alto de una imagen en una función DESPUÉS del cargador, y seguí obteniendo 0. Siento que esto podría ser lo que estás buscando, sin embargo, ya que funciona para mí:

tempObject.image = $('<img />').attr({ 'src':"images/prod-" + tempObject.id + ".png", load:preloader });
xmlProjectInfo.push(tempObject);

function preloader() {
    imagesLoaded++;
    if (imagesLoaded >= itemsToLoad) { //itemsToLoad gets set elsewhere in code
        DetachEvent(this, 'load', preloader); //function that removes event listener
        drawItems();
    }   
}

function drawItems() {
    for(var i = 1; i <= xmlProjectInfo.length; i++)
        alert(xmlProjectInfo[i - 1].image[0].width);
}
 0
Author: Stephen Synowsky,
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-09-11 20:34:10

Echa un vistazo a este repositorio en github!

Gran ejemplo para comprobar el Ancho y Alto usando Javascript

Https://github.com/AzizAK/ImageRealSize

---Editado se solicita a partir de algunos comentarios ..

Código Javascript:

 function CheckImageSize(){
var image = document.getElementById("Image").files[0];
           createReader(image, function (w, h) {

                alert("Width is: " + w + " And Height is: "+h);
});            
}


  function  createReader(file, whenReady) {
        var reader = new FileReader;
        reader.onload = function (evt) {
            var image = new Image();
            image.onload = function (evt) {
                var width = this.width;
                var height = this.height;
                if (whenReady) whenReady(width, height);
            };
            image.src = evt.target.result;
        };
        reader.readAsDataURL(file);
    }

Y código HTML:

<html>
<head>
<title>Image Real Size</title>
<script src="ImageSize.js"></script>
</head>
<body>
<input type="file" id="Image"/>
<input type="button" value="Find the dimensions" onclick="CheckImageSize()"/>
</body>
<html>
 0
Author: Abdulaziz Alkharashi,
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-11-30 08:00:10