JS - get image width and height from the base64 code JS - get image width and height from the base64 code javascript javascript

JS - get image width and height from the base64 code


var i = new Image(); i.onload = function(){ alert( i.width+", "+i.height );};i.src = imageData; 


For synchronous use just wrap it into a promise like this:

function getImageDimensions(file) {  return new Promise (function (resolved, rejected) {    var i = new Image()    i.onload = function(){      resolved({w: i.width, h: i.height})    };    i.src = file  })}

then you can use await to get the data in synchronous coding style:

var dimensions = await getImageDimensions(file)


I found that using .naturalWidth and .naturalHeight had the best results.

const img = new Image();img.src = 'https://via.placeholder.com/350x150';img.onload = function() {  const imgWidth = img.naturalWidth;  const imgHeight = img.naturalHeight;  console.log('imgWidth: ', imgWidth);  console.log('imgHeight: ', imgHeight);};