Search code examples
javascriptimagecanvastodataurl

Uploading image bytes instead of base64 representation


Given a canvas in javascript, the normal workflow to save to a backend server is the following:

  1. Create canvas element
  2. Draw / modify canvas
  3. Call canvas.toDataURL()
  4. Upload this base64 representation of the canvas to your backend server (basic ajax).

Since the call to toDataURL() can be very slow, I'm wondering if it is possible to directly upload image bytes to a backend server, as opposed to the base64 way using toDataURL().

Any ideas?


Solution

  • Use toBlob which returns a blob -or binary- object, instead of toDataURL. you can send the result directly to server. the call is async though

    myCanvas.toBlob(function(myBlob) {
      // send blob to server here!!
    }, "image/jpeg", 0.5);
    

    NB: older MS doesn't support it but see the link in top for a shim. there are better shims out there tho.