¿Existe una forma confiable e independiente del marco de determinar las dimensiones físicas de un <img src='xyz.jpg'>redimensionado en el lado del cliente?
Respuestas:
Tienes 2 opciones:
Opción 1:
Retire las widthy los heightatributos y leer offsetWidthyoffsetHeight
Opcion 2:
Cree un Imageobjeto JavaScript , configure el srcy lea el widthy 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 : Como se acordó en los comentarios, cambié la función para que se ejecute en el evento ´onload´ de la imagen. De lo contrario, con imágenes grandes, heighty widthno devolvería nada porque la imagen aún no se cargó.
newImg.onloadfunción para asegurarme de que la imagen se cargue cuando configuro el ancho / alto. ¿Estás de acuerdo con que edite tu respuesta en consecuencia?
if(newImg.complete || newImg.readyState === 4) newImg.onload();al final de su función, solucionará el problema en Chrome / OSX que hace que la carga no se active cuando las imágenes se cargan desde el caché.
Las imágenes (en Firefox al menos) tienen una naturalWidthpropiedad / height para que pueda usar img.naturalWidthpara obtener el ancho original
var img = document.getElementsByTagName("img")[0];
img.onload=function(){
console.log("Width",img.naturalWidth);
console.log("Height",img.naturalHeight);
}
/* 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);
elementQué es una selección de jQuery? ¿Qué pasa con la altura?
Simplemente cambiando un poco la segunda opción de Gabriel, para que sea 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:
<img id="_temp_circlePic" src="http://localhost/myimage.png"
style="width: 100%; height:100%">
Llamada de muestra:
getImgSize($("#_temp_circlePic").attr("src"), function (imgSize) {
// do what you want with the image's size.
var ratio = imgSize.height / $("#_temp_circlePic").height();
});
img.onload = function () {console.log(img.height, img.width)}