Reputation: 850
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?
Upvotes: 6
Views: 10320
Reputation: 13270
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.
Upvotes: 1
Reputation: 3138
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.
Upvotes: 14