首页 > 解决方案 > 如何在Nodejs中将base64解码为图像?

问题描述

我正在通过套接字发送编码为 base64 的图像,但解码不起​​作用。必须包含新图像的文件被写为 base64 而不是 jpg 文件。

编码套接字:

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')

})

解码插座:

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

标签: javascriptnode.jsstreambuffer

解决方案


更改编码功能,如下所示。另外,请记住 new Buffer() 已被弃用,因此请使用 Buffer.from() 方法。

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

并解码如下:

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

推荐阅读