The working approach to encoding base64 images is to use the Canvas and toDataURL() methods, but you need to load the image data from the server to the Image istance (via the src property). Here is an example:
function getBase64() { var canvas = document.createElement('canvas'); var ctx = canvas.getContext("2d"); var img = new Image(); img.onload = function () { ctx.drawImage(img, 0, 0);
Preferably, you can base64-encoder your server- side image and return a response to the client already encoded. For example, in PHP:
$pathToImg = 'myfolder/myimage.png'; $type = pathinfo($pathToImg, PATHINFO_EXTENSION); $data = file_get_contents($pathToImg); $base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
source share