Node js convert image to base64 Example
In this article, we will explain to you how to convert image to base64 string in node js(Node js convert image to base64 Example). sometimes we need to convert image file to base64 encoding.
If you want to convert an image file to base64 then you can there are two ways such as simple process and third-party npm package.
Node Js Application Setup
First, we will open the command prompt and create the application in our directory. for this, you can follow the below command.
1 2 3 | mkdir my_node_app cd my_node_app npm init |
Install NPM Package
After the done setup node js application, we will install the express npm package for routing. so you can see the following npm command.
1 | npm install express --save |
Example 1
In this example, we will convert the image to a string using simple ways. so you can see the following example.
server.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | var express=require('express'); var app = express(); var fs = require('fs'); function base64_encode(file) { return "data:image/png;base64,"+fs.readFileSync(file, 'base64'); } app.get('/',function(req,res){ var base64str = base64_encode('test.png'); }); app.listen(3000,function(){ console.log("Express Started on Port 3000"); }); |
Example 2
In this example, we will encode image into base64 string using the node-base64-image npm module. so you can see the following example.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | var express=require('express'); var app = express(); var base64 = require('node-base64-image'); app.get('/',function(req,res){ var options = {string: true}; base64.base64encoder('test.png', options, function (err, image) { if (err) { console.log(err); } console.log(image); }); }); app.listen(3000,function(){ console.log("Express Started on Port 3000"); }); |
Run Node js Application
we will run the node js application using the below command. so you can follow the below command.
1 | node server.js |
Now you can run the example using the below Url in the browser.
1 | http://localhost:3000 |