Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In node.js: How to convert jpg images to binaries data?

And on the contrary, how can I convert the binaries data back to image? Because the image data save in the backend are stored as binaries.

like image 612
hh54188 Avatar asked Dec 05 '22 03:12

hh54188


2 Answers

Try this .

var fs = require("fs");

fs.readFile('image.jpg', function(err, data) {
  if (err) throw err;

  // Encode to base64
  var encodedImage = new Buffer(data, 'binary').toString('base64');

  // Decode from base64
  var decodedImage = new Buffer(encodedImage, 'base64').toString('binary');
});

Hope it will be useful for you.

like image 98
Arkar Aung Avatar answered Jan 06 '23 10:01

Arkar Aung


You can do it by using fs.createReadStream instead of Buffer, Buffer is deprecated method. Find more info about the differences in https://medium.com/tensult/stream-and-buffer-concepts-in-node-js-87d565e151a0

like image 25
Vamsi Krishna Avatar answered Jan 06 '23 10:01

Vamsi Krishna