Sharp: Is HTML5 Canvas DataURL format Supported?

Created on 20 Oct 2014  路  3Comments  路  Source: lovell/sharp

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?

question

Most helpful comment

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) { ... })

All 3 comments

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);
  });
});
Was this page helpful?
0 / 5 - 0 ratings

Related issues

zhump picture zhump  路  3Comments

kachurovskiy picture kachurovskiy  路  3Comments

emmtte picture emmtte  路  3Comments

jaydenseric picture jaydenseric  路  3Comments

Andresmag picture Andresmag  路  3Comments