Upload image and grab its dimensions

Asked

Viewed 30 times

1

When executing:

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

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

2 answers

1

Quite possibly your image is not being loaded 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 may be called by several reasons. Among them:

  • The estate src is empty or void
  • The estate src has a URL equal to the page the user is on
  • The image you tried to upload is corrupted
  • The 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 is successfully loaded, the property width and height shall 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);

0


One way I found it was:

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.