Home > Blockchain >  How to get the dimensions of Base64 encoded image in JavaScript
How to get the dimensions of Base64 encoded image in JavaScript

Time:01-26

I have REST API return base64 image:

API response

Is there any way to get dimensions (height, width) of this image?

CodePudding user response:

You can create an Image object with the given src and directly access the width and height properties.

let url = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIAAAAyCAIAAACRXR/mAAABp0lEQVR4nO2YzarqMBRG08bUaicRFIWCmSgUnPj z BUEQQrxYBQrdCiVMnPGfTCvehtztmj42CvUUv297GSQAf1VqsV Tz83xb4P6gFAbUgoBYE1IKAWhBQCwJqQUAtCKgFAbUgfKhWx7283W7ruiaEhGGYJImU8nK5dLtdIUQYht 2v8QJIT9scGlZaz3PWy6XzWtVVff7fbFYVFV1PB5ns5nb6SUOanBd4uPxMMas1 vNZlOW5e12GwwGlFLO fP5tNY2Y fzOU1TQsjhcMjzvC1OCGlrgGnVdc0YS5JECJFlmda60/lzur7vG2Oa5 FwaK3d7/fGmNFo1Ba31rY1vOO6RM4555wQEkURY4xSqrVulrTWvv93S PxeLfbzedzR1wp5Wh4wXVaeZ6naaqUqqrKGBNFUVEUSqnr9RoEged5zZi1VkoZx7GU8t97eYkzxtoa3vEcv0aMMVmWlWUZBMF0Ou33 1LKoigYY0KIXq/XjEkpKaWTyeR0Ommt4zhuizfD7w0wrV/kQz nqAUBtSCgFgTUgoBaEFALAmpBQC0IqAXhCy1TEI1gV/YFAAAAAElFTkSuQmCC';
// same image as https://via.placeholder.com/50x50
let img = new Image();
img.src = url;
img.onload = function() {
  console.log(img.width, img.height);
}
document.body.append(img); // just for demonstration

CodePudding user response:

There are several ways to get the dimensions of an image encoded in base64 format.

One way is to decode the base64 string back to binary data and then use a library like jimp or sharp to read the dimensions of the image. Here's an example using jimp:

const Jimp = require("jimp");

const base64Image = "data:image/png;base64,iVBORw0KGg.....";

Jimp.read(Buffer.from(base64Image.split(",")[1], "base64"), (err, image) => {
  if (err) {
    console.error(err);
  } else {
    console.log(`Width: ${image.bitmap.width}`);
    console.log(`Height: ${image.bitmap.height}`);
  }
});

Another way is to use the atob() function to convert the base64 string to a binary string and then create a Blob object from the binary string and pass it to an Image object, and finally you can use the .naturalWidth and .naturalHeight properties of the Image object to get the dimensions of the image.

let image = new Image();
let binaryString = atob(base64Image.split(",")[1]);
let len = binaryString.length;
let bytes = new Uint8Array(len);
for (let i = 0; i < len; i  )        {
   bytes[i] = binaryString.charCodeAt(i);
}
let blob = new Blob([bytes], {type: 'image/png'});

image.src = URL.createObjectURL(blob);

console.log(`Width: ${image.naturalWidth}`);
console.log(`Height: ${image.naturalHeight}`);
  • Related