Skip to content

Instantly share code, notes, and snippets.

@chayn1k
Forked from MarkoCen/convertImgToBase64.js
Created May 18, 2017 14:38
Show Gist options
  • Save chayn1k/c90bbc6fdd596061af96d29ca0ffc42b to your computer and use it in GitHub Desktop.
Save chayn1k/c90bbc6fdd596061af96d29ca0ffc42b to your computer and use it in GitHub Desktop.
Read Image (PNG/JPEG) From Disk and Convert it to base64-encoded string on Node Server
var express= require('express');
var http = require('http');
var fs = require('fs');
var path = require('path');
var app = express();
server = http.createServer(app);
app.set('view engine', 'jade');
app.get('/readPNG', function(req, res){
//read image file
fs.readFile(process.cwd()+'/pics/demopic.png', function(err, data){
//error handle
if(err) res.status(500).send(err);
//get image file extension name
var extensionName = path.extname(process.cwd()+'/pics/demopic.png');
//convert image file to base64-encoded string
var base64Image = new Buffer(data, 'binary').toString('base64');
//combine all strings
var imgSrcString = "data:image/"+extensionName.split('.').pop()+';base64,'+base64Image;
//send image src string into jade compiler
res.render('index', {imgSrcString: imgSrcString});
})
});
server.listen(2222);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment