本文介绍了nodejs在缓冲区和字符串之间转换图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想将png图像从 buffer 转换为 string ,然后将字符串转换为buffer.
i want to convert png image from buffer to string, and then convert string to buffer.
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 })但是新缓冲区不再是旧缓冲区.
but the new buffer is not old buffer any more.
推荐答案Buffer.toString()的默认编码为 utf8 ,并且您无法从转换> utf8 返回 Buffer ,而不会破坏图像.
Buffer.toString() default encoding is utf8, and you can't convert from utf8 back to Buffer without breaking the image.
如果要转换为字符串,然后再返回到缓冲区,则需要使用允许该编码的编码,例如 base64 .
If you want to convert to string, and then back to buffer, you will need to use an encoding that allows this, for example 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在缓冲区和字符串之间转换图像
发布评论