如何在 Nodejs 中将 base64 解码为图像?

how to decode base64 to image in Nodejs?

我正在通过套接字发送编码为 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

像下面这样更改编码函数。另外,请记住 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')
});

您可以使用以下方法解码 base64 图像。

已编辑

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

注意:-不要忘记这里的{编码:'base64'},你会很高兴的。

似乎是解码函数base64_decode获取数据作为缓冲区。 因此,new Buffer(base64str, 'base64') 中的编码参数被忽略。 (比较 Buffer.from(buffer) vs Buffer.from(string[, encoding]) 的文档)。

我建议先转成字符串

function base64_decode(base64str, file) {

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

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

您可以使用Buffer.from解码Base64,然后使用fs.writeFileSync

将其写入文件
const { writeFileSync } = require("fs")

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

writeFileSync("image.png", image)

如果你的文件中有Base64字符串,你需要先将它解码成字符串,比如:

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

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

writeFileSync("image.png", image)