Solo tengo una URL a una imagen. Necesito determinar la altura y el ancho de esta imagen usando solo JavaScript. La imagen no puede ser visible para el usuario en la página. ¿Cómo puedo obtener sus dimensiones?
Solo tengo una URL a una imagen. Necesito determinar la altura y el ancho de esta imagen usando solo JavaScript. La imagen no puede ser visible para el usuario en la página. ¿Cómo puedo obtener sus dimensiones?
Respuestas:
var img = new Image();
img.onload = function(){
var height = img.height;
var width = img.width;
// code here to use the dimensions
}
img.src = url;
onloadantes que configurar la URL de la imagen?
onloades un oyente al que se llamará asincrónicamente si la imagen se carga correctamente. Si configura el oyente después de configurar la URL, la imagen podría cargarse justo antes de que el código alcance la configuración de la carga, lo que provocará que nunca se llame al oyente. Usando analogías, si te estás sirviendo un vaso con agua, ¿primero viertes el agua y luego pones el vaso para llenarlo? ¿O primero pones el vaso y luego viertes el agua?
Hacer una nueva Image
var img = new Image();
Selecciona el src
img.src = your_src
Obtener el widthy elheight
//img.width
//img.height
Esto usa la función y espera a que se complete.
http://jsfiddle.net/SN2t6/118/
function getMeta(url){
var r = $.Deferred();
$('<img/>').attr('src', url).load(function(){
var s = {w:this.width, h:this.height};
r.resolve(s)
});
return r;
}
getMeta("http://www.google.hr/images/srpr/logo3w.png").done(function(test){
alert(test.w + ' ' + test.h);
});
var img = document.createElement("img");
img.onload = function (event)
{
console.log("natural:", img.naturalWidth, img.naturalHeight);
console.log("width,height:", img.width, img.height);
console.log("offsetW,offsetH:", img.offsetWidth, img.offsetHeight);
}
img.src = "image.jpg";
document.body.appendChild(img);
// css for tests
img { width:50%;height:50%; }
si tiene un archivo de imagen de su formulario de entrada. puedes usar así
let images = new Image();
images.onload = () => {
console.log("Image Size", images.width, images.height)
}
images.onerror = () => result(true);
let fileReader = new FileReader();
fileReader.onload = () => images.src = fileReader.result;
fileReader.onerror = () => result(false);
if (fileTarget) {
fileReader.readAsDataURL(fileTarget);
}
Pregunta similar hecha y respondida usando JQuery aquí:
Obtener ancho alto de la imagen remota de la URL
function getMeta(url){
$("<img/>").attr("src", url).load(function(){
s = {w:this.width, h:this.height};
alert(s.w+' '+s.h);
});
}
getMeta("http://page.com/img.jpg");
Obtenga el tamaño de la imagen con jQuery
function getMeta(url){
$("<img/>",{
load : function(){
alert(this.width+' '+this.height);
},
src : url
});
}
Obtenga el tamaño de la imagen con JavaScript
function getMeta(url){
var img = new Image();
img.onload = function(){
alert( this.width+' '+ this.height );
};
img.src = url;
}
Obtenga el tamaño de la imagen con JavaScript (navegadores modernos, IE9 +)
function getMeta(url){
var img = new Image();
img.addEventListener("load", function(){
alert( this.naturalWidth +' '+ this.naturalHeight );
});
img.src = url;
}
Utilice lo anterior simplemente como: getMeta (" http://example.com/img.jpg ");
https://developer.mozilla.org/en/docs/Web/API/HTMLImageElement
El siguiente código agrega el alto y el ancho del atributo de imagen a cada imagen en la página.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Untitled</title>
<script type="text/javascript">
function addImgAttributes()
{
for( i=0; i < document.images.length; i++)
{
width = document.images[i].width;
height = document.images[i].height;
window.document.images[i].setAttribute("width",width);
window.document.images[i].setAttribute("height",height);
}
}
</script>
</head>
<body onload="addImgAttributes();">
<img src="2_01.jpg"/>
<img src="2_01.jpg"/>
</body>
</html>