Convert an image to base64 in Node.js

Hello geeks, in this blog, we will learn how to convert an image to base64 in node.js. The tutorial will be step by easy step process of converting images into a base64 in this node js.

Base64 Encoding In Node.js:-
• sending binary data over a text-based protocol such as HTTP.
• It ensures text does not get corrupted during transfer.
• It does not conceal data.

In the below example you can see the Basic encoding and decoding code where  we send binary data over a text-based protocol such as HTTP ensuring that the  text does not get corrupted during transfer:

<body>
<h1>Base64 Encoding</h1>
<script>
const str = "dcode";
const base64 = btoa(str);//converting to base64
const decoded = atob(base64);//converting to orginal string

//printing output in console

console.log("Original: " + str);
console.log("Base64: " + base64);
console.log("Decoded: " + decoded);
</script>
</body>

Output:

Original: dcode 
Base64: ZGNvZGU= 
Decoded: dcode

Now we will see how we can convert the image file to base64:

In this example, you will learn node js convert image files to base64. I will give you a simple solution with a full example of how to convert an image to a base64  in node js. let’s see the solution with an example.

Here we have used The readFileSync() method that is used to read the content of a file synchronously which means a statement has to wait for the earlier statement to get executed, so your JavaScript code execution will not be stopped until the method is finished. Also, synchronous files run step by step, and readFileSync is also used to read files and return content.

var base64str = base64_encode('image.png');

function base64_encode(file) {

return "data:image/gif;base64,"+fs.readFileSync(file, 'base64');

Example of converting image file to base64:
const express = require('express');
const fs = require('fs');
const app = express();
  
var base64str = base64_encode('image.png');
console.log(base64str);
  
function base64_encode(file) {
    return "data:image/gif;base64,"+fs.readFileSync(file, 'base64');
}
  
app.listen(3000);

Thanks for Reading I hope you find this helpful.

Leave a Reply

Your email address will not be published.