node.jsnpmbase64image-size

NodeJS: How to use image-size with base64 image?


I found the node module image-size and want to use it to get the dimensions of a base64 encoded image. The tutorial gives the following example for getting the dimensions:

var sizeOf = require('image-size');
var dimensions = sizeOf('images/funny-cats.png');
console.log(dimensions.width, dimensions.height);

An here in the comment of the second answer someone wrote it's working for base64 images as well. So I tried the follwing:

var img = Buffer.from(base64, 'base64');
var dimensions = sizeOf(img);
console.log(dimensions.width, dimensions.height);

But I get a TypeError: unsupported file type: undefined (file: undefined)

How can I use sizeOf-Method of the image-size package with a base64 string I have in a variable?


Solution

  • Try this

    var img = Buffer.from(base64.substr(23), 'base64');
    var dimensions = sizeOf(img);
    console.log(dimensions.width, dimensions.height);
    

    substr(23) cuts off data:image/jpeg;base64,, which is necessary to properly create a Buffer from your base64 data.