-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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