nodejs在缓冲区和字符串之间转换图像

时间:2019-04-03 02:20:14

标签: node.js image png buffer

我想将png图片从buffer转换为string,然后将字符串转换为缓冲区。

fs.readFile('/Users/xxx/Desktop/1.png', (err, data) => {
    if (err) throw err; // Fail if the file can't be read.
    data = Buffer.from(data)
    let str = data.toString()
    data = Buffer.from(str)
});

// server
router.register('/api/dump', (request, response) => { 
    fs.readFile('/Users/xxx/Desktop/1.png', (err, data) => {
        if (err) throw err; // Fail if the file can't be read. 
        response.writeHead(200, {'Content-Type': 'image/jpeg'}); 
        response.end(data); // Send the file data to the browser.
    });
}) 

// front
this.$get('/dump').then(result => {
    // i want to convert result to buffer
})

但是新缓冲区不再是旧缓冲区。

1 个答案:

答案 0 :(得分:0)

Buffer.toString()的默认编码为utf8,在不破坏图像的情况下,您不能从utf8转换回Buffer

如果要转换为字符串,然后再返回到缓冲区,则需要使用允许这种编码的编码,例如base64

fs.readFile('/Users/yihchu/Desktop/1.png', (err, data) => {
    if (err) throw err; // Fail if the file can't be read.
    var oldData = data;
    let str = data.toString('base64')
    data = Buffer.from(str, 'base64');
});