Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nodejs convert image between buffer and string

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.

like image 897
2218 Avatar asked Oct 28 '25 07:10

2218


1 Answers

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');
});
like image 117
Marcos Casagrande Avatar answered Oct 31 '25 00:10

Marcos Casagrande



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!