Get image width and height from the Base64 code in JavaScript
Asked Answered
S

6

128

I have a Base64 image encoded that you can find here. How can I get the height and the width of it?

Soemba answered 21/7, 2013 at 17:24 Comment(2)
Link rot has set in for this questionMacintosh
Yep. "Hmm. We’re having trouble finding that site. We can’t connect to the server at soo.gd."Disruptive
A
190
var i = new Image();

i.onload = function(){
  alert(i.width + ", " + i.height);
};

i.src = imageData;
Aponeurosis answered 21/7, 2013 at 18:6 Comment(8)
too bad that this is an asynchronous process.Leucopoiesis
@CoenDamen yep. I need synchronous process as well.Pend
I would also add that the order here is very important. If you do this the other way around (src before onload) you may miss the event. See: https://mcmap.net/q/75729/-waiting-for-image-to-load-in-javascriptIsopropanol
@CoenDamen why should the whole script block just to get information on the image size?Phenanthrene
can't we do it without loading the image from the string ?Conde
string or url, the image has to be loaded for client to get the dimension. do you have something else in mind?Aponeurosis
imageData should be in the format data:image/png;base64, then the base 64 image data.Macintosh
To get width and height synchronously inside an asyc function you can use decode() as described in one of the other answers: stackoverflow.com/a/71804221Famed
C
54

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)
Chink answered 7/3, 2018 at 19:21 Comment(2)
It's still asynchronous though. Just using syntactic sugar.Oestrin
'naturalWidth' and 'naturalHeight` are the better choices no? #28167637Wiggs
E
26

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);
};

Documentation:

This is only supported in modern browsers. NaturalWidth and NaturalHeight in IE

Eugenioeugenius answered 14/11, 2014 at 16:15 Comment(1)
Exactly, it is the original size of image before being resized by object-fitArliearliene
F
12

A more modern solution is to use HTMLImageElement.decode() instead of the onload event. decode() returns a promise and thus can be used synchronously with await.

Asynchronous use:

let img = new Image();
img.src = "myImage.png";
img.decode().then(() => {
    let width = img.width;
    let height = img.height;
    // Do something with dimensions
});

Synchronous use (inside an async function):

let img = new Image();
img.src = "myImage.png";
await img.decode();
let width = img.width;
let height = img.height;
// Do something with dimensions
Famed answered 8/4, 2022 at 23:59 Comment(1)
Awesome answer, learned something new today.Dowsabel
J
1

Create a hidden <img> with that image and then use jQuery's .width() and . height()

$("body").append("<img id='hiddenImage' src='" + imageData + "' />");
var width = $('#hiddenImage').width();
var height = $('#hiddenImage').height();
$('#hiddenImage').remove();
alert("width:" + width + " height:" + height);

Test here: JSFiddle

The image is not initially created hidden. It gets created, and then you get width and height and then remove it. This may cause a very short visibility in large images. In this case, you have to wrap the image in another container and make that container hidden, not the image itself.


Another Fiddle that does not add to the DOM as per gp.'s answer: here

Jae answered 21/7, 2013 at 17:26 Comment(3)
var i = new Image(); i.src = imageData; setTimeout(function(){ alert ( "width:"+ i.width+" height:" + i.height ); },100);Aponeurosis
this is only a fix needed because of the nature of the jsfiddle, you can change onLoad to onDomReady instead to fix that initial 0 width and height problem. Code assumes you call this function somewhere in your work where document is already loaded.Jae
Guess your point being was, that you do not need to add anything to dom to get width and height. Will modify answer to reflect your suggestions.Jae
L
-1
const img = new Image();
img.src = dataUrl;
await img.decode();
const width, height =  img.width, img.height;
Lashanda answered 18/4, 2023 at 1:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.