Convert html image object to base64 encoded text

From Code Trash
Jump to: navigation, search

Convert the html image object in binary form to a base64 encoded string to for posting it to another server through ajax

function getDataUrl(img) {
   // Create canvas
   const canvas = document.createElement('canvas');
   const ctx = canvas.getContext('2d');
   // Set width and height
   canvas.width = img.width;
   canvas.height = img.height;
   // Draw the image
   ctx.drawImage(img, 0, 0);
   return canvas.toDataURL('image/jpeg');