8

I have converted the contents of a canvas element to data (URI Scheme) using toDataURL() ($contact_image_data) and I want to send this via email as an attachment. This is currently how I have PHPMailer set up:

$contact_image_data="data:image/png;base64,iVBORw0KGgo[...]";
$filename="test.png"; 
$encoding = "base64"; 
$type = "image/png";
$mail->AddStringAttachment($contact_image_data, $filename, $encoding, $type);   

I am wondering if this is actually possible, and if so, what steps I am missing.

I can send an email, attach a file named “test.png” which contains the contents of $contact_image_data, but it doesn’t actually create an image.

Any help would be much appreciated.

Samuel.

Samuel Cotterall
  • 343
  • 1
  • 2
  • 9

2 Answers2

18

It turns out I needed to strip the data:image/png;base64, section and base64_decode() the data:

$contact_image_data="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAA";
$data = substr($contact_image_data, strpos($contact_image_data, ","));
$filename="test.png"; 
$encoding = "base64"; 
$type = "image/png";
$mail->AddStringAttachment(base64_decode($data), $filename, $encoding, $type);          
Samuel Cotterall
  • 343
  • 1
  • 2
  • 9
  • If you don't want to substr the DataURI, you can also get the data with `file_get_contents` like this: `$data = file_get_contents($contact_image_data);` – Mendy Jan 14 '19 at 19:29
2

Yes it should be possible. Are you calling toDataURL() with the 'image/png' MIME type so it knows how to output it?

Try breaking your script into two components - make sure you really have a PNG then try mailing it.

For example, will test.png open on your computer when written?..

<?php
$contact_image_data="data:image/png;base64,iVBORw0KGgo[...]";
$fp = fopen('test.png', 'w');
fwrite($fp, $contact_image_data);
fclose($fp);
?>

Hope that helps a bit!

Al.
  • 2,872
  • 2
  • 22
  • 34
  • Thank you, That was really helpful—it was only after playing with `fwrite` that I found this http://canvaspaint.org/blog/2007/01/saving-images/#comments which gave me my answer. Cheers! – Samuel Cotterall Jul 29 '09 at 19:43
  • Archived version of the link referred in above comment: https://web.archive.org/web/20110305022152/http://canvaspaint.org/blog/2007/01/saving-images/ – danShumway Aug 05 '14 at 05:20