繁体   English   中英

如何在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 图像。

已编辑

去除标题

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'} 在这里,你会很高兴的。

似乎解码函数base64_decode将数据作为缓冲区获取。 因此, new Buffer(base64str, 'base64')的 encoding 参数被忽略。 (比较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 ********');
  }

您可以使用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 } = require("fs")

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

writeFileSync("image.png", image)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM