繁体   English   中英

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

[英]nodejs convert image between buffer and string

我想将 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
})

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

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

暂无
暂无

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

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