televisores son smart samsung mejores mejor los cuales cual javascript jquery image size

son - ¿Puede Javascript acceder al tamaño de la imagen nativa?



sony o samsung tv (5)

Estoy escribiendo una función jQuery en la que me gustaría acceder tanto al tamaño nativo de una imagen como al tamaño especificado para ella en la página. Me gustaría establecer una variable para cada uno.

¿Cómo se hace eso?


Navegadores modernos

Cuando escribí esta respuesta en 2009, el panorama del navegador era muy diferente. Hoy en día, cualquier navegador razonablemente moderno es compatible con la sugerencia de Pim Jager utilizando img.naturalWidth y img.naturalHeight . Echa un vistazo a su respuesta.

Respuesta legada compatible con navegadores super antiguos.

// find the element var img = $(''#imageid''); /* * create an offscreen image that isn''t scaled * but contains the same image. * Because it''s cached it should be instantly here. */ var theImage = new Image(); theImage.src = img.attr("src"); // you should check here if the image has finished loading // this can be done with theImage.complete alert("Width: " + theImage.width); alert("Height: " + theImage.height);


Esto debería funcionar:

var img = $(''#imageid'')[0]; //same as document.getElementById(''imageid''); var width = img.naturalWidth; var height = img.naturalHeight;

NaturalWidth y naturalHeight devuelven el tamaño de la respuesta de la imagen, no el tamaño de visualización.

De acuerdo con el comentario de Josh, esto no es compatible con el navegador cruzado, esto podría ser correcto, lo probé en FF3


Estoy agregando una manera de lograr esto y estar seguro de que hay soporte para todos los navegadores. Casi todos los navegadores son compatibles con naturalWidth y naturalHeight excepto para Internet Explorer 8 y anteriores.

Ya que IE 8 e inferior devolverían el tamaño de la imagen visible y no el tamaño natural cuando intentamos recuperar valores de tamaño, se necesita una pequeña solución para obtener las dimensiones de tamaño completo que provienen de un ejemplo de Jack Moore .

function naturalSize(imageid) { imageid = (imageid.src ? imageid : document.getElementById(imageid)); if (document.documentMode < 9) { var img = new Image(); img.src = imageid.src; return {width: img.width,height: img.height}; } return {width: imageid.naturalWidth,height: imageid.naturalHeight}; }

Configuré esto para admitir pasar el valor de ID de imagen o el nombre de ID.

Uso:

<img src="http://c64.exitof99.com/ims/VicGauntlet2013.png" id="some_img" width="400"> naturalSize("some_img"); // Returns: Object {width: 731, height: 387}

O

<img src="http://c64.exitof99.com/ims/VicGauntlet2013.png" onclick="aaa=naturalSize(this);alert(''Size: ''+aaa.width+''x''+aaa.height);"> // Displays: Size: 731x387

Asegúrese de asegurarse de que la imagen esté cargada antes de llamarla, ya sea mediante el uso de onload o la activación al agregarla al DOM.

Probado con: Windows XP - Firefox 1.5, IE 8 Windows 7 - IE 9, Chrome 56 Android 6.0.1 - Chrome 50 Android 5.1.1 - Opera Mini 7.6, Dolphin 10.3

Ejemplo de código completo:

<!DOCTYPE html> <html dir="LTR" lang="en"><head> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title></title> </head> <body class="assignments" onload="run_test();"> <img src="http://c64.exitof99.com/ims/VicGauntlet2013.png" id="some_img" width="400"> <textarea id="outbox"></textarea> <script type="text/javascript"> function naturalSize(imageid) { imageid = (imageid.src ? imageid : document.getElementById(imageid)); if (document.documentMode < 9) { var img = new Image(); img.src = imageid.src; return {width: img.width,height: img.height}; } return {width: imageid.naturalWidth,height: imageid.naturalHeight}; } function run_test() { var a = naturalSize("some_img"); document.getElementById("outbox").innerHTML = "Size: "+a.width+"x"+a.height; } </script> </body></html>


Mi solución sería escribir un servicio web que obtenga / descargue la imagen, luego obtenga su resolución y la devuelva como {ancho: x, altura: y}. Luego lo llamas con $ .ajax o equivalente para recuperar esto.

Alternativamente, puedes agregar la imagen a un div oculto usando

// e.g. don''t set width and height $("#hiddendiv").html("<img src=''theurl''>");

Y luego obtén el ancho / alto del div, aunque no lo he probado.