I have a base64 encoded image returned from a service and it looks like this:
/9j/4AAQSkZJRgABAQEASABIAAD/4Yp2aHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wLwA8P3hwYWN
This one will work for any extension type: pdf, mp3, png, ....
base64.substring(base64.indexOf('/') + 1, base64.indexOf(';base64'));
A bit late, but you can do it using the file-type module in Node.JS:
npm install file-type
var fileType = require("file-type");
var base64string = "/9j/4AAQSkZJRgABAQEASABIAAD/4Yp2aHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wLwA8P3hwYWNrZXQgYmVnaW49Iu+7vyIgaWQ9Ilc1TTBNcENlaGlIenJlU3pOVGN6a2M5ZCI/Pgo8eDp4bXBtZXRhIHhtbG5zOng9ImFkb2JlOm5zOm1ldGEvIiB4OnhtcHRrPSJBZG9iZSBYTVAgQ29yZSA0LjEtYzAzNiA0Ni4yNzcwOTIsIEZyaSBGZWIgMjMgMjAwNyAxNDoxNjoxOCAgICAgICAgIj4KICAgPHJkZjpSREYgeG1";
var base64string_buffer = Buffer.from(base64string, "base64");
(async ()=>{
var result = await fileType.fromBuffer(base64string_buffer);
console.log(result);
//Returns { ext: 'jpg', mime: 'image/jpeg' }
})();
According to file-type
's npm page, it works on getting the magic number which can be found in the returned buffer item. For example, a jpeg starts with ff d8
, a pdf with 25 50 44 46
, etc.
For reference, here's a snippet from base64string_buffer.toString('hex').match(/../g).join(' ')
:
ff d8 ff e0 00 10 4a 46 49 46 00 01 01 01 00 48 00 48 00 00 ff e1 8a 76 68 74 74 70 .....