AliAb
AliAb

Reputation: 569

how to decode base64 to image in Nodejs?

I'm sending an image encoded as base64 through sockets and decoding is not working. The file that must contain the new image is written as base64 instead of a jpg file.

encoding socket:

function encode_base64(filename) {
  fs.readFile(path.join(__dirname, filename), function (error, data) {
    if (error) {
      throw error;
    } else {
      console.log(data);
      var dataBase64 = data.toString('base64');
      console.log(dataBase64);
      

      client.write(dataBase64);
    }
  });
}

rl.on('line', (data) => {
    encode_base64('../image.jpg')

})

decoding socket:

function base64_decode(base64str, file) {
  
   var bitmap = new Buffer(base64str, 'base64');
   
   fs.writeFileSync(file, bitmap);
   console.log('****** File created from base64 encoded string ******');
  }


client.on('data', (data) => {


    base64_decode(data,'copy.jpg')

  
});

// the first few characters in the new file 
//k1NRWuGwBGJpmHDTI9VcgOcRgIT0ftMsldCjFJ43whvppjV48NGq3eeOIeeur

Upvotes: 9

Views: 41848

Answers (4)

Alphka
Alphka

Reputation: 90

You can use a Buffer.from to decode the Base64, and write it to a file using fs.writeFileSync

const { writeFileSync } = require("fs")

const base64 = "iVBORw0KGgoA..."
const image = Buffer.from(base64, "base64")

writeFileSync("image.png", image)

If you have the Base64 string inside a file, you need to decode it into string first, like:

const { writeFileSync, readFileSync } = require("fs")

const base64 = readFileSync(path, "ascii")
const image = Buffer.from(base64, "base64")

writeFileSync("image.png", image)

Upvotes: 3

Sandeep Patel
Sandeep Patel

Reputation: 5148

Change encode function like below. Also, keep in mind new Buffer() has been deprecated so use Buffer.from() method.

function encode_base64(filename) {
  fs.readFile(path.join(__dirname, filename), function (error, data) {
    if (error) {
      throw error;
    } else {
      //console.log(data);
      var dataBase64 = Buffer.from(data).toString('base64');
      console.log(dataBase64);
      client.write(dataBase64);
    }
  });
}

And decode as Below :

function base64_decode(base64Image, file) {
  fs.writeFileSync(file,base64Image);
   console.log('******** File created from base64 encoded string ********');

}

client.on('data', (data) => {
    base64_decode(data,'copy.jpg')
});

Upvotes: 9

Pushprajsinh Chudasama
Pushprajsinh Chudasama

Reputation: 7969

You can decode the base64 image using following method .

EDITED

To strip off the header

let base64String = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgA'; // Not a real image
// Remove header
let base64Image = base64String.split(';base64,').pop();

To write to a file

import fs from 'fs';
fs.writeFile('image.png', base64Image, {encoding: 'base64'}, function(err) {
    console.log('File created');
});

Note :- Don’t forget the {encoding: 'base64'} here and you will be good to go.

Upvotes: 15

Avraham
Avraham

Reputation: 938

It seems that the decoding function base64_decode gets the data as a buffer. Thus, the encoding argument in new Buffer(base64str, 'base64') is ignored. (Compare the docs of Buffer.from(buffer) vs Buffer.from(string[, encoding])).

I suggest to convert to a string first

function base64_decode(base64str, file) {

   var bitmap = new Buffer(base64str.toString(), 'base64');

   fs.writeFileSync(file, bitmap);
   console.log('******** File created from base64 encoded string ********');
  }

Upvotes: 1

Related Questions