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

7
我正在通过套接字发送一个以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
4个回答

13
你可以使用以下方法解码base64图像。 编辑

要去掉头部

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

写文件

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

注意:不要忘记在这里加上{encoding: 'base64'},这样你就可以顺利进行了。


它给了我一个错误: DeprecationWarning: Buffer()由于安全和可用性问题而被弃用, 所以我将其更改为Buffer.from(data,“base64”) 但文件仍以base64编写,而不是jpg。 - AliAb
尝试为您提供另一种解决方案。 - Pushprajsinh Chudasama
我已经更新了我的代码,你可以去看看。@AliHmede - Pushprajsinh Chudasama
什么是image.png?如何访问它的结果? - Grogu
Image.png是你想要的文件名,结果可以在名为image.png的文件中看到/访问。@Grogu - Pushprajsinh Chudasama

9

请将编码函数更改为以下内容。同时需要注意新的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')
});

数据是字符串吗? - Sandeep Patel
在 "client.write(dataBase64)" 中,数据是字符串。 - AliAb
非常感谢您的帮助,但该文件仍在写入Base64字符。 - AliAb
数据类型是缓冲区。 - AliAb
它是用于写入缓冲区的TCP套接字吗? - Sandeep Patel
显示剩余5条评论

2

您可以使用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)

1
似乎解码函数 base64_decode 会将数据作为缓冲区传入。因此,在 new Buffer(base64str, 'base64') 中的编码参数会被忽略。(与 Buffer.from(buffer)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 ********');
  }


文件“not base64 even”中出现了奇怪的字符。 - AliAb
好的。实际上这是另一个问题,因为k1NRWuGwBGJpmHDTI9VcgOcRgIT0ftMsldCjFJ43whvppjV48NGq3eeOIeeur不是一个有效的base64字符串。尝试使用console.log打印写入客户端的前10个字符以及base64_decode函数接收到的前10个字符。 - Avraham

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接