NodeJS: How to use image-size with base64 image?
Asked Answered
W

2

6

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?

Wayless answered 21/2, 2019 at 10:24 Comment(2)
Is your base64 variable declared?Interrogative
yes it is. Sorry is just the snippet for the code. The variable is passed to the function and is valid (tested)Wayless
J
14

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.

Jitterbug answered 21/2, 2019 at 11:30 Comment(1)
it's better to use base64.split(';base64,').pop() because it can be png image and you should substr(22) in this caseAmoral
R
1

Here's another solution using puppeteer worth considering

const puppeteer = require('puppeteer')

// image data
const data = 'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBwgHBg...'

const browser = await puppeteer.launch()
const page = await browser.newPage();

const dimensions = await page.evaluate(data => new Promise(resolve => {
  // client-like
  const img = new Image()
  img.onload = () => resolve({ width: img.width, height: img.height })
  img.src = data
}), data)

console.log(dimensions.width, dimensions.height)
browser.close()

Use this if the code is run in a wsl context :

const browser = await puppeteer.launch({
  args: ['--no-sandbox', '--disable-setuid-sandbox']
})

NOTE : Of course this method is really slow (because it opens a Chromium instance in the background, loads a webpage and its scripts, waits for rendering, etc...). I am providing this solution just for reference as in some cases being able to execute a script just like in a normal browser can be really useful.

Rimarimas answered 4/6, 2022 at 11:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.