Reputation: 41
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.
Upvotes: 4
Views: 20544
Reputation: 40404
Buffer.toString()
default encoding is utf8
, and you can't convert from utf8
back to Buffer
without breaking the image.
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');
});
Upvotes: 6