2009-12-22 11 views

Respuesta

114

tiene 2 opciones:

Opción 1:

Retire los width y height atributos y leer offsetWidth y offsetHeight

Opción 2:

Crear un JavaScript Image objeto, configure el src, y lea width y height (ni siquiera tiene que agregarlo a la página para hacer esto).

function getImgSize(imgSrc) { 
    var newImg = new Image(); 

    newImg.onload = function() { 
     var height = newImg.height; 
     var width = newImg.width; 
     alert ('The image size is '+width+'*'+height); 
    } 

    newImg.src = imgSrc; // this must be done AFTER setting onload 
} 

Editar por Pekka: Según lo acordado en los comentarios, me cambió la función a ejecutar en el evento'onload' de la imagen. De lo contrario, con imágenes grandes, height y width no devolverían nada porque la imagen aún no se había cargado.

+0

Eso no funcionará con las imágenes que aún no están cargadas. Puede valer la pena ajustarlo para que funcione correctamente para que otras personas tropiecen con esta respuesta. – James

+8

@Gabriel, estoy usando esto pero con una función 'newImg.onload' para asegurarme de que la imagen se cargue cuando configuro el ancho/alto. ¿Estás de acuerdo conmigo editando tu respuesta en consecuencia? –

+0

Eso no es un problema –

3

Puede precargar la imagen en un objeto de imagen javascript, luego verificar las propiedades de ancho y alto en ese objeto.

+0

Por supuesto - no lo hago tiene que ponerlo en el documento. Lo haré de esa manera, ¡salud! –

67

Imágenes (en Firefox por lo menos) tienen una propiedad naturalWidth/altura de esta manera puede utilizar img.naturalWidth para obtener la anchura original

var img = document.getElementsByTagName("img")[0]; 
img.onload=function(){ 
    console.log("Width",img.naturalWidth); 
    console.log("Height",img.naturalHeight); 
} 

Source

+6

También funciona en Chrome – bcoughlan

+2

También funciona en IE9 +, pero no en IE8 – fero

+4

Este tema sigue siendo relevante en 2013. Aquí hay un enlace con una gran solución para IE7/8: http://www.jacklmoore.com/notes/naturalwidth- and-naturalheight-in-ie / – BurninLeo

2
/* Function to return the DOM object's in crossbrowser style */ 
function widthCrossBrowser(element) { 
    /* element - DOM element */ 

    /* For FireFox & IE */ 
    if( element.width != undefined && element.width != '' && element.width != 0){ 
     this.width = element.width; 
    } 
    /* For FireFox & IE */ 
    else if(element.clientWidth != undefined && element.clientWidth != '' && element.clientWidth != 0){ 
     this.width = element.clientWidth; 
    } 
    /* For Chrome * FireFox */ 
    else if(element.naturalWidth != undefined && element.naturalWidth != '' && element.naturalWidth != 0){ 
     this.width = element.naturalWidth; 
    } 
    /* For FireFox & IE */ 
    else if(element.offsetWidth != undefined && element.offsetWidth != '' && element.offsetWidth != 0){ 
     this.width = element.offsetWidth; 
    }  
     /* 
      console.info(' widthWidth width:',  element.width); 
      console.info(' clntWidth clientWidth:', element.clientWidth); 
      console.info(' natWidth naturalWidth:', element.naturalWidth); 
      console.info(' offstWidth offsetWidth:',element.offsetWidth);  
      console.info(' parseInt(this.width):',parseInt(this.width)); 
     */ 
    return parseInt(this.width); 

} 

var elementWidth = widthCrossBrowser(element); 
3

Simplemente cambiando un poco la segunda opción de Gabriel , para ser más fácil de usar:

function getImgSize(imgSrc, callback) { 
    var newImg = new Image(); 

    newImg.onload = function() { 
     if (callback != undefined) 
      callback({width: newImg.width, height: newImg.height}) 
    } 

    newImg.src = imgSrc; 
} 

HTML: llamada

<img id="_temp_circlePic" src="http://localhost/myimage.png" 
style="width: 100%; height:100%"> 

muestra:

getImgSize($("#_temp_circlePic").attr("src"), function (imgSize) { 
    // do what you want with the image's size. 
    var ratio = imgSize.height/$("#_temp_circlePic").height(); 
}); 
Cuestiones relacionadas