Get height and width of an image before loading it with Javascript

1

No jQuery or similar

The href that are stored in the link variable are images that are not found in the DOM

I want to save the values of the height and width of X number of images of different proportions with a for cycle, but the way I am doing it does not work (it generates zeros) since the image has not finished loading. This is what I wear:

var img = document.getElementsByClassName('post-image');
var link, w, h;

var margenes = [];

for(var i = 0; i < img.length; i++){
    // La url de la imagen
    link = img[i].parentElement.href;

    // Agregar <img src="link"> al DOM, esto va dentro de un <div>
    document.getElementById('thread').insertAdjacentHTML('afterbegin', '<div id="lightbox"><img id="lightbox-img" src="' + link + '"></div>');

    // Obtener los valores de alto y ancho
    var lightboxImg = document.getElementById('lightbox-img');
    w = lightboxImg.width;
    h = lightboxImg.height;

    // Guardar una cadena de texto en el arreglo con los datos de alto y ancho
    margenes.push("-" + h/2 + "px 0px 0px -" + w/2 + "px");


    console.log(margenes[i]);

    // Eliminar la imagen del DOM
    document.getElementById('lightbox').parentNode.removeChild(document.getElementById('lightbox'));
}

The line

console.log(margenes[i]);

I generate -0px 0px 0px -0px

I want to save everything in the margins array because I use that string afterwards to add CSS. If there is a way to store in the h and w variables the height and width values before loading the image or in any other way that does not require the image to be DOM I ask you to let me know.

    
asked by akko 17.05.2017 в 08:16
source

2 answers

1

Try the getBoundingClientRect () function, which returns the position and size of an HTML element. For example:

let images = document.querySelectorAll('.post-images');

for (let image of images) {
  let imageSize = image.getBoundingClientRect();
  console.log('width: ${imageSize.width}, height: ${imageSize.height}');
}
    
answered by 17.05.2017 в 09:30
1

window.onload = function {...} What it does is first load the page and then execute the function. Within this you will have to put the for . If this still does not work the code to follow is the following:

window.URL = window.URL || window.webkitURL;
var elBrowse = document.getElementById("browse"),
  elPreview = document.getElementById("preview"),
  useBlob = false && window.URL; // Set to 'true' to use Blob instead of Data-URL

// 2.
function readImage() {

  // Creauna nueva instancia de FileReader 
  // https://developer.mozilla.org/en/docs/Web/API/FileReader
  var reader = new FileReader();
  var file = document.getElementById('browse').files[0];
  reader.readAsDataURL(file);

  // Una vez ya ha sido leído:
  reader.addEventListener("load", function() {

    // En este punto 'reader.result' contiene Base64 Data-URL
    // y podriamos mostrar inmediatamente la imagen usando
    // 'elPreview.insertAdjacentHTML("beforeend", "<img src='"+ reader.result +"'>");'
    // Pero buscamos el ancho y el alto de la imagen en px
    // Como el archivo Objeto no contiene el tamaño de la imagen
    // Necesitamos crear una nueva imagen y asignar su src asi que
    // cuando la image este cargada podemos calcular el alto y ancho de esta
    var image = new Image();
    image.src = reader.result;
    image.addEventListener("load", function() {

      // Concatenatar nuestro HTML image info 
      var imageInfo = file.name + ' ' + // Obtener el valor del 'name' desde el archivo obj
        image.width + '×' + // Obtener el ancho de nuestra imagen
        image.height + ' ' +
        file.type + ' ' +
        Math.round(file.size / 1024) + 'KB';

      // Finally append our created image and the HTML info string to our '#preview' 
      elPreview.appendChild(this);
      elPreview.insertAdjacentHTML("beforeend", imageInfo + '<br>');

    });
  });

}
#preview img {
  height: 100px;
}
<input id="browse" type="file" multiple onchange="readImage()">
<div id="preview"></div>
    
answered by 17.05.2017 в 08:29