Convert Base64 to Image in Node JS

It is easy to convert a Base64 encoded image to an image file in Node JS. In this article, we will learn how to convert a Base64 encoded image to an image file and write it into the file system.

How to convert Base64 to Image?

To convert base64 to an image in Node.js, use the fs.writeFileSync() method.

This method accepts two parameters file destination path where you want to write a file on disk and Buffer data.

Node JS
const fs = require("fs");

const checkBase64FileType = (firstChar) => {
  switch (firstChar) {
    case "/":
      return "jpg";
    case "i":
      return "png";
    case "R":
      return "gif";
    case "U":
      return "webp";
    default:
      return null;
  }
};

const base64 = "iVBORw0KGgoAAAANSUhEUgAAASwAAAEsBAMAAACLU5NGAAAAG1BMVEXMzMyWlpacnJyqqqrFxcWxsbGjo6O3t7e+vr6He3KoAAAACXBIWXMAAA7EAAAOxAGVKw4bAAAD90lEQVR4nO3cwW+bSBQH4AcGw5HnJDhHaN3dHO1su9ojNGnPtrUb7dFuIiVHnEo5263Uv3vfGwab1myVA5DV6vcpgeD35HmeGYbJxUQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD/zOb3N5BRexlu9/Jo+NCQFl/HbWrRK7s6Amcdy3jCfaftyOT/OmsnLxSFqkzu04Ns1Z+RxPOMtUc63fH6U5HP8O5/uo1Vyh9IJhTylwSjz0pV0y4Tex0dJ7iij3ck+WiV3J9RPvVhRLgO5O5V+KOSl7MesnXSRH++jNrlDAWurEW0i6ZOz8jI9mlwaDXkftckd8nXEdgnNVjI2sf6Q+VvLSMiMHJnupHC0j9rkrmlL87Lhs7JK86oM1fowVFq0jdrkjn2QKbMuTEvD8aGsfCQ9th9PbzHeR21yt1KWkUq3et+Tq4tDHpnXfZ67+7Zdltu1itrkbrEuRWVLWdmwHbl0shlXSQ7LLVtFbXLXZUmLphHOHK3IsWVtTg6Lk6PFV1Gb3G1Z9I1Xjb015NpSHq7jfntL7reoaW7JhD+pJQ2537llVuyGO1Em17iWJMt7f3ei/zeZcdGlKLDr1saW5XPV9F9bM2pV1CZ3yDxDZFx0HZcF0z+s8rpwVcuWPo5k1KqoTe7QwD58mp6Js/PUTn4tVEatx2ei3lAzu4M4t3uErQl5PN3YOb84NR+gitrkDnl8J51QNO23hjLH7SqQxxnp0trbfotmo9t0RE27U9k9hFw2PuBfLnVD0d/u9KMs8hNq2svrxFqXJXprZtmg9riXp5v0jTRI4afyn5lv1X8+gRaQ22XA/zT6sxatkgEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD65tjf/5gXLYtHb/8l8kNZkVw5zEwjIjei8ru7rtJ7/YqcO3ISorTFsiLvt+eXZY7xlp5sWd6b7KscrpeZ80DBus2y6D1dviY3C+QP/9WUnGWkp8GrhZa1fE3DQiK1ssYrurdlDeblwZ86TzTctFuWf/dxPihy+kw31+/IuTOnm2v98I6EwoTe1cuKLsLEluVm5cFLHHf7pc2JKIPoZl4STpfFHzSRfnEyc5pQrmVJiO7l13yRHpdlPQ0LW5ZTHSInWN23WZZMedMJycUq0aa1FT1F1dyK6MugoHpvuY903Fv0a9Jqb+n7apesHlY0KSvRU6233CV9V5Z/RsdzixbzlsvSuUXL4nFOT9mVtq2nw9yiYPx9WebCHGt3IrW7yOnby51IuyzPKEgv9M31dLgTKUgayioH+oqrdavlsp5hWPTb3jM9vnQBjZyLl64AAP43/gHVSaMe2vmdiAAAAABJRU5ErkJggg==";

const fileExtension = checkBase64FileType(base64[0]);

if (!fileExtension) {
  throw new Error("Invalid file type or Invalid data string");
}
const buffer = Buffer.from(base64, "base64");
fs.writeFileSync(`new-file.${fileExtension}`, buffer);

As you can see in the above example, converting base64 to an image is 4 step process.

  1. Import the fs module
  2. Check file type
  3. Convert base64 to buffer
  4. Convert Buffer to image

1. Import the fs module

Node JS
const fs = require("fs");

2. Check file type

We need a file extension to store the file on a local disk.

To check file type from base64, we need to check the first character of the base64 string.

We can check the base64 file type using the following characters.

CharacterExtension
/jpg
ipng
Rgif
Uwebp
Node JS
const checkBase64FileType = (firstChar) => {
  switch (firstChar) {
    case '/':
        return 'jpg';
    case 'i':
      return 'png';
    case 'R':
      return 'gif';
    case 'U':
      return 'webp';
    default:
      return null;
  }
}

We used a switch case to check each case and returned an extension.

Also, we wrote a default case where we return null because if we are not able to find the file type, it must be an invalid file or an invalid data string.

3. Convert base64 to buffer

After checking the file type, we need to convert it to Buffer.

To convert Buffer, use Buffer.from(), which accepts two parameters data string and encoding type.

Node JS
//👇️ <Buffer 89 50 4e 47 0d 0a 1a 0a 00 00... more bytes>
const buffer = Buffer.from(base64, "base64"); 

We passed the base64 data string as the first parameter and base64 as the second parameter.

4. Convert Buffer to image

Finally, its time to convert Buffer to the image.

Using fs.writeFileSync() method, we can convert Buffer data to an image file.

Node JS
fs.writeFileSync('destination-path/image.jpg', buffer);

The fs.writeFileSync() method accepts 2 parameters destination path and buffer data.

If you want to convert image to base64 you can check the article: Convert Image to base64 in Node JS.


Conclusion

In conclusion, to convert base64 to an image in Node.js, convert base64 to Buffer and use that Buffer to convert it to the image.


Learn more:

Unlock your programming potential with Stack Thrive! Discover step-by-step tutorials, insightful tips, and expert advice that will sharpen your coding skills and broaden your knowledge.

Leave a Comment

Facebook Twitter WhatsApp