base64 to png nodejs

Converting Base64 to PNG with Node.js

If you're working with images in Node.js, there may be times when you need to convert a Base64 encoded string to a PNG image file. Fortunately, this can be done using some built-in Node.js modules.

Method 1: Using the Buffer Module

The first method involves using the Buffer module to decode the Base64 string and then writing the resulting binary data to a file with a .png extension.

const fs = require('fs');

// Base64 encoded string
const base64String = 'iVBORw0KGgoAAAANSUhEUgAAAAUA...';

// Decode the string
const binaryData = Buffer.from(base64String, 'base64');

// Write the data to a file
fs.writeFile('image.png', binaryData, (err) => {
  if (err) throw err;
  console.log('The file has been saved!');
});

This code reads in a Base64 encoded string and decodes it using the Buffer.from() method, which takes the string as its first argument and the encoding type as its second argument (in this case, 'base64'). The resulting binary data is then written to a file with a .png extension using the fs.writeFile() method.

Method 2: Using the Node-Base64 Image Module

If you prefer a more streamlined approach, you can use the node-base64-image module to convert the Base64 string directly to a PNG image file.

const base64Img = require('base64-img');

// Base64 encoded string
const base64String = 'iVBORw0KGgoAAAANSUhEUgAAAAUA...';

// Convert to image file
base64Img.img(base64String, '.', 'image', (err, filepath) => {
  if (err) throw err;
  console.log('The file has been saved!');
});

Here, the base64-img module is used to convert the Base64 string to an image file. The img() method takes the string to convert as its first argument, the directory to save the image in as its second argument, and a file prefix as its third argument (in this case, 'image'). The resulting filepath is returned in the callback function.

Conclusion

Both of these methods allow you to easily convert a Base64 encoded string to a PNG image file in Node.js. Which method you choose will depend on your specific use case and personal preference.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe