Upload image and get its dimensions

1

When running:

var image = new Image();
image.src = "./image.png";
var w = image.width;

Is the variable 'w' equal to '0', is there a way to capture the dimensions of the 'image'?

    
asked by anonymous 16.08.2018 / 02:52

2 answers

1

Quite possibly your image is not loading correctly. Try the following:

var img = new Image();

img.onerror = function() {
  console.warn("Ocorreu um erro ao carregar a imagem");
}

// esta imagem não existe.
// troque pelo caminho para a sua imagem
img.src = "http://www.apimages.com/Images/Ap_Creative_Stock_Header_blah.jpg";

console.log(img.width);

The handler onerror can be called by various reasons . Among them:

  • The src property is empty or null
  • The src property has a URL equal to the page where the user is located
  • The image you tried to upload is corrupted
  • Image does not exist
  • Image metadata is corrupted (making it impossible to analyze image dimensions)
  • The image is in a format not supported by your browser

After the image loads successfully, the width and height property will have the dimensions of the image loaded.

var img = new Image();

img.onerror = function() {
  console.log("Ocorreu um erro ao carregar a imagem");
}

// esta imagem existe
img.src = "http://www.apimages.com/Images/Ap_Creative_Stock_Header.jpg";
console.log(img.width);
document.body.appendChild(img);
    
16.08.2018 / 10:07
0

One way I found it was:

var image = new Image();
image.src = './image.png';
image.onload = function () {
   var w = image.width;
}
    
17.08.2018 / 11:37