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

编程入门 行业动态 更新时间:2024-10-27 20:28:22
本文介绍了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在缓冲区和字符串之间转换图像

本文发布于:2023-06-11 15:11:29,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/637407.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:缓冲区   字符串   图像   nodejs

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!