Hi Guys,
I am trying to find a solution where I convert an image upload on the front-end into a data string format, which is essentially a base64 style string, using HTML5 Canvas API.
I then send this string to the back-end. What I wanted to ask is if there is a way for me to use the 'sharp' library so that it can load and process this data string so I can perform some operations (mainly resize in to new images).
Is this possible?
The toDataURL() method of an HTML5 canvas returns base64-encoded PNG image data (you can request JPEG data by using toDataURL('image/jpeg').
Assuming image is a String containing base64-encoded data, either PNG or JPEG, then you should be able to use something like the following:
sharp(new Buffer(image, 'base64')).resize(width, height).toBuffer(function(err, data) { ... })
Ah fantastic, I currently do use JPEG data using 'image/jpeg'.
One last clarification, will the toBuffer give back the same format JPEG data in base64 so that I can send it back as is to the front-end for rendering?
If you'd like the output image data to be a base64-encoded string you can use data.toString('base64').
If you simply need the browser to display the output JPEG image then you can send the Buffer directly. Here's an example using Express:
route.get(..., function(req, res) {
...
sharp(...).resize(...).toBuffer(function(err, data) {
res.header('Content-Type', 'image/jpeg').send(data);
});
});
Most helpful comment
The
toDataURL()method of an HTML5 canvas returns base64-encoded PNG image data (you can request JPEG data by usingtoDataURL('image/jpeg').Assuming
imageis a String containing base64-encoded data, either PNG or JPEG, then you should be able to use something like the following:sharp(new Buffer(image, 'base64')).resize(width, height).toBuffer(function(err, data) { ... })