3

I have a page where users can create their own SVG images. Now I would like to access these images on the server (php) so they can be sent to an email address.

With these instructions I am able to convert the SVG to a canvas and then convert the canvas to jpeg/png. I'm not worried about the SVG tree anymore as it doesn't need to be edited anymore, thus converting it to a normal image (I was assuming that would be easier to handle, ultimately I want to send that image as an attachment in the email).

What would be the most efficient way of doing this? Is it possible to POST the converted jpeg/png to the server? Thanks guys, kinda lost here.

Community
  • 1
  • 1
enp4yne
  • 638
  • 5
  • 21
  • 1
    What about posting the svg to the server and doing the conversion there? – pintxo Sep 09 '12 at 20:32
  • I've thought about that too, but I still wouldn't know how to send the SVG to the server? :) Wouldn't I need to serialize it in some way? – enp4yne Sep 09 '12 at 20:40

1 Answers1

4

After a lot more reading I managed to find a fairly simple solution, in case anyone has a similar problem here it is:

Once you have converted the SVG to a normal canvas using canvg you can make use of the canvas.toDataURL() method, all you need to do then is POST the generated URL and decode it on the server. I used a hidden input field for this. Be careful not to use JQuery for getting the canvas, since JQuery doesn't return the actual canvas but a JQuery Object.

var canvas = document.getElementById('canvas');
var dataUrl = canvas.toDataURL();
$('#hiddenInput').val(dataUrl);

And on the server side:

$encodeData = $_POST['dataUrl'];
$encodeData = substr($encodeData, strpos($encodeData, ',') + 1); //strip the URL of its headers
$decodeData = base64_decode($encodeData);
$handle = fopen('test.png', 'x+');
fwrite($handle, $decodeData);
fclose($handle);

The SVG is now on the server as a png.

enp4yne
  • 638
  • 5
  • 21