I
I
Ivan Ivanovich2021-01-05 13:15:04
Node.js
Ivan Ivanovich, 2021-01-05 13:15:04

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

2 answer(s)
W
WbICHA, 2021-01-05
@WblCHA

https://nodejs.org/api/buffer.html#buffer_static_m...

encoding <string> The encoding of string. Default: 'utf8'.

He reads your line as utf8, not base64, change it. Why are you using a string instead of a buffer?
fromBuffer('bufferhere');

I
Ivan Ivanovich, 2021-01-05
@IwanQ

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 question

Ask a Question

731 491 924 answers to any question