validar tamaño tablas seleccionar modificar insertar imagenes imagen ejemplos dimensiones con cambiar javascript jquery image jquery-plugins

tamaño - tablas en javascript ejemplos



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

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

window.onload=function(){ console.log(img.offsetWidth,img.offsetHeight); }

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


Antes de utilizar el tamaño de imagen real, debe cargar la imagen de origen. Si utiliza el marco JQuery, puede obtener el tamaño de imagen real de una manera sencilla.

$("ImageID").load(function(){ console.log($(this).width() + "x" + $(this).height()) })


Con jQuery library-

Utilice .width() y .height() .

Más en jQuery width y jQuery heigth .

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>


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á obsoleto.

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 imagen API. Indica que la height y la width son la altura / anchura representada de la imagen y que naturalHeight y naturalWidth son la altura / anchura intrínseca de la imagen (y son solo HTML5).

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 utilicé 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

Entonces 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

Entonces cambié el HTML a lo siguiente:

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

Es decir, utilizando 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


Lo que todos los demás han olvidado es que no puedes verificar el tamaño de la imagen antes de cargarla. Cuando el autor verifique todos los métodos publicados, probablemente funcionará solo en localhost. Ya que jQuery podría usarse aquí, recuerde que el evento "listo" se dispara antes de que se carguen las imágenes. $ (''# xxx''). width () y .height () deben activarse en el evento onload o posterior.


Nicky De Maeyer preguntó por una imagen de fondo; Simplemente lo obtengo del css y sustituyo el "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())); }


Puede aplicar la propiedad del controlador de carga cuando la página se carga en js o jquery de esta manera:

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


Puede obtener la imagen mediante programación y verificar las dimensiones utilizando 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 es parte del marcado.


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

// 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.


Respuesta de JQuery:

$height = $(''#image_id'').height(); $width = $(''#image_id'').width();


Si está utilizando jQuery y solicita 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()); }); });


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>


Solo puede hacer esto realmente usando una devolución de llamada del evento de carga, ya que el tamaño de la imagen no se conoce hasta que realmente se haya terminado de cargar. Algo como el siguiente código ...

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


También (además de las respuestas de Rex y 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).


También puedes usar:

var image=document.getElementById("imageID"); var width=image.offsetWidth; var height=image.offsetHeight;


Usando JQuery haces esto:

var imgWidth = $("#imgIDWhatever").width();


es importante eliminar la configuración interpretada del navegador del div principal. Así que si quieres el ancho y la altura de la imagen real puedes usar

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

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


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 se habría llamado a la siguiente declaración antes de cargar el archivo 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'']); }


clientWidth y clientHeight son propiedades DOM que muestran el tamaño actual en el navegador de las dimensiones internas de un elemento DOM (excluyendo el margen y el borde). Entonces, 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;


This respuesta fue exactamente lo que estaba buscando (en jQuery):

var imageNaturalWidth = $(''image-selector'').prop(''naturalWidth''); var imageNaturalHeight = $(''image-selector'').prop(''naturalHeight'');


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]); }

este trabajo para múltiples imágenes de vista previa y carga. Si tiene que seleccionar para cada una de las imágenes una por una. Luego copie y pegue en toda la función de imagen de vista previa y valide!


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 ...


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 sea útil. :)