how to decode base64 to image in Nodejs?
Asked Answered
I

4

9

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
Islington answered 11/9, 2019 at 9:24 Comment(0)
S
9

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')
});
Spiculate answered 11/9, 2019 at 9:36 Comment(10)
the terminal of the receiving socket gave this error: TypeError: base64str.split is not a function at base64_decode (C:\Users\HP\Desktop\Node\sockets\client2.js:17:28)Islington
is data string?Spiculate
on " client.write(dataBase64) " the data is stringIslington
the terminal wrote it "File created from base64 encoded string" but the jpg file is still written as base64 (no image is made)Islington
Can you give one more try I have changed decode method code a bitSpiculate
thank you a lot for helping me but the file is still writing a base64 charactersIslington
can you check data type of 'data' at receiving end?Spiculate
the data type is bufferIslington
is it TCP socket for writing buffer?Spiculate
yes, a the encoding socket is client sending to server then send it to another client. i am using this: var net = require('net'); var client = new net.Socket();Islington
A
15

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.

Androsphinx answered 11/9, 2019 at 9:37 Comment(5)
it gave me an error: DeprecationWarning: Buffer() is deprecated due to security and usability issues so i changed it to Buffer.from(data, "base64") but the file is still written in base64 not as jpgIslington
try to give you another solution .Androsphinx
I have updated my code , you can check it out . @AliHmedeAndrosphinx
What is image.png? And how do you access result of this?Medea
Image.png is a file name you wanted to be, and result is seen/access in file named image.png @MedeaAndrosphinx
S
9

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')
});
Spiculate answered 11/9, 2019 at 9:36 Comment(10)
the terminal of the receiving socket gave this error: TypeError: base64str.split is not a function at base64_decode (C:\Users\HP\Desktop\Node\sockets\client2.js:17:28)Islington
is data string?Spiculate
on " client.write(dataBase64) " the data is stringIslington
the terminal wrote it "File created from base64 encoded string" but the jpg file is still written as base64 (no image is made)Islington
Can you give one more try I have changed decode method code a bitSpiculate
thank you a lot for helping me but the file is still writing a base64 charactersIslington
can you check data type of 'data' at receiving end?Spiculate
the data type is bufferIslington
is it TCP socket for writing buffer?Spiculate
yes, a the encoding socket is client sending to server then send it to another client. i am using this: var net = require('net'); var client = new net.Socket();Islington
T
3

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)
Troth answered 1/1, 2022 at 2:59 Comment(0)
S
1

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 ********');
  }

Scale answered 11/9, 2019 at 9:52 Comment(2)
strange characters appeard in the file "not base64 even" ���Islington
Right. Actually it's another issue, because k1NRWuGwBGJpmHDTI9VcgOcRgIT0ftMsldCjFJ43whvppjV48NGq3eeOIeeur is not a valid base64 string. Try to console.log the first 10 characters written to the client with the first 10 chars received by the base64_decode function.Scale

© 2022 - 2024 — McMap. All rights reserved.