Converting base64 to image in JS

Soldato
Joined
27 Dec 2005
Posts
17,288
Location
Bristol
I'm using jq-signature (https://github.com/bencentra/jq-signature) to give me a signature field on a form, but I'm struggling to interpret its output via ajax/php.

Gathering the field via var signature = $().jqSignature('getDataURL'); is fine, but if I try to straight output that with a .html(signature); for example, the output is "[object Object]".

I'm not 100% on what format the variable signature is in there, and how to convert it to a string (ideally). String would be ideal as the ajax can then pass the string (as opposed to an image) to a php mail script.

I've tried used atob() and btoa() with no success but I'm rubbish at js and it's difficult to troubleshoot.

TIA!
 
Soldato
Joined
3 Jun 2005
Posts
3,066
Location
The South
It returns a string which is a base64 encoded PNG image, albeit with a prefix, MIME type and base64 option (https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs), ie - 'data:image/png;base64,'.

As @touch says, you can dump this straight to a image tag otherwise you can happily parse it via a form/AJAX etc, strip out the prefix (after the comma is the encoded data) and then either use that encoded data or decode it via PHP (https://www.php.net/manual/en/function.base64-decode.php) and output to a file etc (https://netcell.netlify.com/blog/2016/04/image-base64.html).
 
Back
Top Bottom