Don Rhummy
Don Rhummy

Reputation: 25830

How would I convert an SVG in a web page that a user draws on to a PNG or JPG?

I have a web page that has an iframe with an SVG which allows the user to draw on it. When they're done, I want to convert their drawing to an image. How would I do this?

(It needs to work in iOS Safari, Chrome, Firefox, Safari desktop, IE9+)

I'd prefer a client-side solution but could PHP solutions are ok.

Upvotes: 0

Views: 315

Answers (2)

Adrian
Adrian

Reputation: 1046

I recently did this for a project I'm working on. There is different approaches, but this is what I went with.

Using jQuery and canvg (http://code.google.com/p/canvg/)

--

My JavaScript function

function getChartData(chartDiv) {

    var svg = $('#' + chartDiv).find('svg').parent().html();
    $('<canvas id="newCanvas_' + chartDiv + '" width="' + $('#' + chartDiv).width() + 'px" height="' + $('#' + chartDiv).height() + 'px" style="display: none; position: absolute; top: 0px; left: 0px; z-index: 0;"></canvas>').insertAfter('body');
    canvg(document.getElementById('newCanvas_' + chartDiv), svg);

    var imgData = document.getElementById('newCanvas_' + chartDiv).toDataURL("image/png");
    return imgData;
}

Then I had my svg element within a DIV.

<div id="mydrawing">
    <svg></svg>
</div>

Then I ran the function to get the base64 encoded string of the SVG as an image.

base64string = getChartData('mydrawing');

Then I could use that variable to display the image in my HTML, or pass it to my PHP to generate an image to save.

<img src="data:image/png;base64, base64string" />

Upvotes: 2

Alvin K.
Alvin K.

Reputation: 4379

A server side solution would be:

  1. Install imagemagick.so module on server
  2. parse the SVG as string and submit it to server (POST recommended)
  3. Insert additional XML tags (if required)
  4. Use PHP::imagemagick to convert it to a PNG or JPG.
  5. Return image to client, include the header declaration.

Note: Server side coding is more reliable, however the down side is graphical processing is heavy on CPU cycles (ie: lots of users may lag your server).

Upvotes: 0

Related Questions