【问题标题】:nodejs convert image between buffer and stringnodejs在缓冲区和字符串之间转换图像
【发布时间】:2019-08-24 10:45:33
【问题描述】:

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

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

【问题讨论】:

  • 路由器代码有什么问题吗,没有问题,和原问题无关,也和上面的sn-p无关。

标签: node.js image png buffer


【解决方案1】:

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

【讨论】:

  • 我用nodejs写了一个服务器,代码是:router.register('/api/dump', (request, response) => { fs.readFile('/Users/yihchu/Desktop/1 .png', (err, data) => { if (err) throw err; // 如果无法读取文件则失败 response.writeHead(200, {'Content-Type': 'image/jpeg'} ); response.end(data); // 将文件数据发送到浏览器。 }); }) 网页收到的响应就像 utf8 中的 toString,我想把它转换成缓冲区
  • 把它放在代码块中,在你原来的问题中,这样它就可以被阅读了。
  • 你想达到什么目的,看来你的问题是别的。
  • this.$get('/dump').then(result => { // 我想将结果转换为缓冲区 }) 结果就像 Buffer.toString('utf8'),我想转换回缓冲区
  • 为什么,为什么前端需要buffer,说明你要达到什么目的,而不仅仅是“我要转换成buffer”,为什么需要buffer。跨度>
猜你喜欢
  • 1970-01-01
  • 2022-01-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-10-07
  • 1970-01-01
  • 2012-08-02
相关资源
最近更新 更多