JS - get image width and height from the base64 code
JavascriptJqueryImageBase64DimensionsJavascript Problem Overview
I have a base64 img encoded that you can find here. How can I get the height and the width of it?
Javascript Solutions
Solution 1 - Javascript
var i = new Image();
i.onload = function(){
alert( i.width+", "+i.height );
};
i.src = imageData;
Solution 2 - Javascript
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)
Solution 3 - Javascript
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);
};
Docs:
- https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/naturalWidth
- https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/naturalHeight
This is only supported in modern browsers. http://www.jacklmoore.com/notes/naturalwidth-and-naturalheight-in-ie/
Solution 4 - Javascript
Create a hidden <img>
with that image and then use jquery .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: FIDDLE
Image is not initially created hidden. it gets created, 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 dom as per gp.'s anser : HERE
Solution 5 - Javascript
A more modern solution is to use decode()
instead of the onload
event. decode()
returns a promise, 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 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