Answer the question
In order to leave comments, you need to log in
How to convert base64 to buffer?
Good day. Faced the following problem.
You need to get the image in base64, then convert it to a buffer for later obtaining information using the file-type package.
When I receive a base64 image, I convert it to a buffer as follows:
I pass the resulting value to the file-type package
But I get undefined.
Please tell me what am I doing wrong?
Buffer.from('base64here');
await FileType.fromBuffer('bufferhere');
Answer the question
In order to leave comments, you need to log in
https://nodejs.org/api/buffer.html#buffer_static_m...
encoding <string> The encoding of string. Default: 'utf8'.
fromBuffer('bufferhere');
Decision:
const decodeBase64Img = (base64String) => {
const matches = base64String.match(/^data:([A-Za-z-+/]+);base64,(.+)$/),
obj = {};
if (matches.length !== 3) {
return new Error('Invalid input string');
}
const [, extension, base64] = matches;
obj.type = extension;
obj.buffer = Buffer.from(base64, 'base64');
return obj;
// Based on: https://stackoverflow.com/Questions/20267939/Nodejs-Write-Base64-Image-File
};
await FileType.fromBuffer(decodeBase64Img('base64').buffer);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question