如何在Nodejs中将base64解码为图像? [英] how to decode base64 to image in Nodejs?

查看:153
本文介绍了如何在Nodejs中将base64解码为图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

编码套接字:

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() 方法.

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

解码如下:

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

这篇关于如何在Nodejs中将base64解码为图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆