Creating Vector Graphics with PHP - php

Im trying to create vector graphics in PHP. Ive tried Cairo and I havn't been able to get it to work. I understand that imageMagick has vector functionality but the documentation on php.net is very poor can some one lead me in the right direction? The ideas is to be able to save the graphic to EPS. I also need to be able to use different fonts to output text.

Although you're looking to create eps I would still aim to create a PDF. PDF's are fully editable in any major package: Adobe Illustrator, Corel Draw, Xara Pro etc
TCPDF works well and there is a bunch of code samples including fonts and support for vector images eps and ai output to PDF
eps/ai example http://www.tcpdf.org/examples/example_032.pdf
All the examples and php code http://www.tcpdf.org/examples.php

I know what this is quite old question, but I had some problem few weeks ago and solve it for myself, hope this answer helps someone.
Cairo library have PHP bindings, but it also have few bugs which break convertation between formats - forget about it. We need something native here on start. Look at SVG format - open your vector image in editor (I use Inkscape) and save it as SVG file. After that you can change it via php just like xml file.
Adding custom fonts in SVG:
$text_path = 'm 100,200'
$font_name = 'Some_font.ttf';
$font_size = '20px';
$font = base64_encode('font_file_content');
$text = 'Bla bla bla';
$font_svg = '<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<defs>
<path d="' . $text_path . '" id="font_id_123"/>
<style type="text/css">
<![CDATA[
#font-face {
font-family: ' . $font_name . ';
src: url("data:font/ttf;charset=utf-8;base64,' . $font . '");
]]>
</style>
</defs>
<text style="font-family: ' . $font_name . '; font-size: ' . $font_size . ';">
<textPath xlink:href="#font_id_123">' . $text . '</textPath>
</text>
</svg>';
$content = file_get_contents($svg_file); // $svg_file - your vector image
$content = substr($content, 0, -6); // cut last '</svg>' tag from file
$newContent = $content . $font_svg . '</svg>'; // add font to the end
file_put_contents($svg_file, $newContent); // save changes
Ok, we have SVG with needed fonts, but we need EPS. For converting SVG to EPS I used Inkscape with simple bash script svg2eps.sh:
#!/bin/bash
inkscape -f $1 -z -T -E $2
You can call it from php:
exec('/path/to/svg2eps.sh /path/to/in.svg path/to/out.eps');
Other tips:
1)Install latest version of Inkscape. I tested it on openSuse 12.3 - works great.
2)Install all custom fonts to system fonts.

Try these links:
http://www.imagemagick.org/script/magick-vector-graphics.php
and
http://www.imagemagick.org/discourse-server/viewtopic.php?f=10&t=10144

I can't tell you how to create vector images in PHP but perhaps you would like a bit different approach- create raster images in PHP and convert them to vectors? It works okay for black & white images not sure about color ones.
<?php
$im = imagecreatetruecolor(500,500);
//draw something on $im
imagepng($im, 'image.png');
$url = 'http://server.com/image.png'; //change to your server's domain
$data = json_decode(file_get_contents('http://api.rest7.com/v1/raster_to_vector.php?url=' . $url . '&format=svg'));
if (#$data->success !== 1)
{
die('Failed');
}
$vec = file_get_contents($data->file);
file_put_contents('vectors.svg', $vec);

Related

imagick setimageformat zero size image string passed error - one of many errors - svg to pdf

Okay, so the problem is essentially: convert an svg to a pdf using image magick.
I take an image in a base64 format, do something to it, convert it to a bitmap, do something to is, store it inside an SVG string, write the svg to a file (doesn't have to be done, but wanted to make sure the svg was loading), then from here I need to convert the svg to a pdf.
//I just broke the string up over spaces for sake of readability
$svgStr = "<?xml version=1.0.' encoding='utf-8' standalone='no'?>
<svg xmlns="http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' xml:space='preserve'>
<desc>
Made by Shane
</desc>
<defs>
</defs>
<style>
</style>
<image width='500' height'auto' xlink:href'" . $path . $filename . $ext . "' />
</svg>";
file_put_contents($path . $svgFile . ".svg", $svgStr);
//Attempt 1 of many
$pdf = New Imagick($path . $svgFile . ".svg", "SVG");
$pdf->setImageFormat("PDF"); //This thows the "Can not process empty imagick object" error.
file_put_contents($path . $svgFile . ".pdf", $pdf);
//Attempt2 of many
$pdf = New Imagick();
//Throws an error here - can not process empty Imagick object...
//which brings me back to attempt 1... the idea in attempt 1 is to initialize
//the Imagick object with the svg format and data, then convert.
//Here the idea is to initialize it step by step
$pdf->setImageFormat("SVG");
//For readImageBlob(), I should be able to read the svg file or use the $svgStr.
$pdf->readImageBlob($svgStr);
$pdf->setImageFormat("PDF");
file_put_contents($path . $svgFile . ".pdf", $pdf);
I am running image magick 6.8.9-9.
I can't upgrade, because I don't have sudo and it can't be accessed is the long story short.
EDIT:
I think this might be part of the problem - I get an error converting a .bmp to a pdf from the command line:
https://askubuntu.com/questions/1081695/error-during-converting-jpg-to-pdf
However, I don't know if the command line utilities operate in the same manner as the class wrapper does...
Please help 0_0
Thank you.

Generate SVG Image using svg raw data in imagick php

I am trying to create svg image using svg raw data which i am getting from fabric js. I have used below code to generate the svg using svg raw data but its not working properly.
public function generate_svg($raw_svg='',$prefix='',$folder_name='card_image')
{
$file_name = '';
if($raw_svg!='')
{
try{
$file_name = uniqid($prefix).".svg";
$image = new \Imagick();
$image->readImageBlob($raw_svg);
$image->setImageFormat("svg");
$image->writeImage($folder_name.$file_name);
} catch (ImagickException $ex) {
echo $ex->getMessage();
}
}
return $file_name;
}
Now the issue is background image is kind of Look like below:
So what should i do to fix that?
It should look like below (ignore the square and round), the issue is whole background looks like black instead of bg image.:
So the issue is background image is not loading, so do i have to add additional library to do that or any thing else?
Imagick Version: 6.7.7
convert -list delegate | grep svg
cdr => "uniconvertor' '%i' '%o.svg'; /bin/mv '%o.svg' '%o"
cgm => "uniconvertor' '%i' '%o.svg'; /bin/mv '%o.svg' '%o"
dot => "dot' -Tsvg '%i' -o '%o"
dxf => "uniconvertor' '%i' '%o.svg'; /bin/mv '%o.svg' '%o"
fig => "uniconvertor' '%i' '%o.svg'; /bin/mv '%o.svg' '%o"
svg => "rsvg-convert' -o '%o' '%i"
convert -list format | grep SVG
MSVG rw+ ImageMagick's own SVG internal renderer
SVG rw+ Scalable Vector Graphics (XML 2.9.1)
SVGZ rw+ Compressed Scalable Vector Graphics (XML 2.9.1)
I think you are on the wrong track. Image Magick is basically a pixel-oriented library. While rendering the background image might be a question of configuration, your picture shows that the font "embedding" you wanted to achieve isn't happening. And there lies the real problem.
What you want to achieve is representing the font information inside the SVG file. There are two ways to do that, and for both there is absolutely no support in IM:
converting the font to the SVG font format and embedding it inline in the file (produces large files)
converting all glyphs to paths (texts are no longer editable)
From your description I think you should be aiming for the second variant. You would basically exchange <text> elements in your string with <path> elements and otherwise write out the SVG file including the embeded image data as you received it.
How to convert text to SVG paths? is an older look at that problem.
EasySVG for PHP is a library that resulted from that question for the glyph-to-path conversion, but only provided you have the font already in SVG format. For typical desktop font formats like ttf, you might first have to look at font conversion tools like FontForge.
You might get a direct svg data transformation working via Cairo, but that is only a hunch, I haven't worked with it.
Finally, as a workaround, you could delegate the whole task to Inkscape. It can be called on the command line without starting the GUI as
inkscape in.svg --export-text-to-path --export-plain-svg=out.svg
I have ended up by storing fonts in raw svg and after that created svg file using fopen instead of using imagick.
So my svg is look like below:
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" width="600" height="400" viewBox="0 0 600 400" xml:space="preserve">
<desc>Created with Fabric.js 2.0.0-beta7</desc>
<defs>
<style>
//... base64 data of font
#font-face {
font-family: "Elsie";
src: url("data:application/font-truetype;charset=utf-8;base64,...")
}
</style>
</defs>
After that i have created svg file using below:
$file_name = uniqid($prefix).".svg";
$file_handle = fopen("$folder_name/".$file_name, 'w');
fwrite($file_handle, $raw_svg);
fclose($file_handle);
In addition to #ccprog's fantastic answer,
I'd like to mention you can generate the pixels you want using phantomjs, just feed the phantomjs with your input html file and output as a png.

Converting HTML to PDF via PHP (install font for html2pdf)

I'm currently attempting to convert HTML markup (from an xml feed) into a PDF dynamically via a PHP script.
From reading other answers the best free way of doing this seemed to be to use html2pdf.
// HTML2PDF
require_once('/public_html/html2pdf/html2pdf.class.php');
$html2pdf = new HTML2PDF('P','A4','en');
$html2pdf->WriteHTML($htmlContent);
$html2pdf->Output('/public_html/wp-content/uploads/rns/html2pdf.pdf');
The problem I'm having is my $htmlContent contains the css: FONT-FAMILY: "Times New Roman","serif" in various places and my script gives the error:
TCPDF ERROR: Could not include font definition file: "times new roman"
I've googled and the only documentation is this:
http://wiki.spipu.net/doku.php?id=html2pdf:en:v4:font
Which in turn leads you to:
http://www.tcpdf.org/fonts.php
I'm lost though, the second link says that times/Times New Roman is a core PDF font... I've tried various things and get the same error.
What would I actually need to write to add the font, or alternatively, how could I strip all of the FONT-FAMILY classes out of the $htmlContent (I don't even need it in any particular font, just one that works).
Yes, you should use DOMPDF instead of other libraries. There are lots of fonts available. You can see at "dompdf/lib/fonts/dompdf_font_family_cache.dist.php" and choose according to your requirements. For change the font you need to change the def("DOMPDF_DEFAULT_FONT", "serif") at file path "dompdf/dompdf_config.inc.php":
You can download the latest version available of DOMPDF from: https://code.google.com/p/dompdf/downloads/detail?name=dompdf_0-6-0_beta3.tar.gz&can=2&q=
See the below example:
require_once("dompdf/dompdf_config.inc.php");
$dompdf = new DOMPDF();
$dompdf->load_html($htmlContent);
$dompdf->render();
$fileName = "invoice.pdf";
$dompdf->stream($fileName);//DOWNLOAD PDF
//GET OUTPUT AS STRING AND PUT IN TO SOME FILE
$output = $dompdf->output();
file_put_contents($fileName, $output);
Try to use DomPdf instead of html2pdf. It works great for me on creating invoices in PDF. But some treatments (positioning and font sizes) in your CSS code are needed. The screen content placed as it is didn't work as i expected.
https://github.com/dompdf/dompdf
It's a bit of a hack, but I found the best way for me was to call capturejs using exec:
$run = "capturejs -u ";
$run .= "https://www.example.com/";
$run .= " -p tlsv1 -V ";
$run .= "1024x768";
$run .= " -o 'myimage.png'";
exec($run);
https://github.com/superbrothers/capturejs

Saving SVG as PNG [duplicate]

I'm working on a web project that involves a dynamically generated map of the US coloring different states based on a set of data.
This SVG file gives me a good blank map of the US and is very easy to change the color of each state. The difficulty is that IE browsers don't support SVG so in order for me to use the handy syntax the svg offers, I'll need to convert it to a JPG.
Ideally, I'd like to do this with only the GD2 library but could also use ImageMagick. I have absolutely no clue how to do this.
Any solution that would allow me to dynamically change the colors of states on a map of the US will be considered. The key is that it is easy to change the colors on the fly and that it is cross browser. PHP/Apache solutions only, please.
That's funny you asked this, I just did this recently for my work's site and I was thinking I should write a tutorial... Here is how to do it with PHP/Imagick, which uses ImageMagick:
$usmap = '/path/to/blank/us-map.svg';
$im = new Imagick();
$svg = file_get_contents($usmap);
/*loop to color each state as needed, something like*/
$idColorArray = array(
"AL" => "339966"
,"AK" => "0099FF"
...
,"WI" => "FF4B00"
,"WY" => "A3609B"
);
foreach($idColorArray as $state => $color){
//Where $color is a RRGGBB hex value
$svg = preg_replace(
'/id="'.$state.'" style="fill:#([0-9a-f]{6})/'
, 'id="'.$state.'" style="fill:#'.$color
, $svg
);
}
$im->readImageBlob($svg);
/*png settings*/
$im->setImageFormat("png24");
$im->resizeImage(720, 445, imagick::FILTER_LANCZOS, 1); /*Optional, if you need to resize*/
/*jpeg*/
$im->setImageFormat("jpeg");
$im->adaptiveResizeImage(720, 445); /*Optional, if you need to resize*/
$im->writeImage('/path/to/colored/us-map.png');/*(or .jpg)*/
$im->clear();
$im->destroy();
the steps regex color replacement may vary depending on the svg path xml and how you id & color values are stored. If you don't want to store a file on the server, you can output the image as base 64 like
<?php echo '<img src="data:image/jpg;base64,' . base64_encode($im) . '" />';?>
(before you use clear/destroy) but ie has issues with PNG as base64 so you'd probably have to output base64 as jpeg
you can see an example here I did for a former employer's sales territory map:
Start: https://upload.wikimedia.org/wikipedia/commons/1/1a/Blank_US_Map_(states_only).svg
Finish:
Edit
Since writing the above, I've come up with 2 improved techniques:
1) instead of a regex loop to change the fill on state , use CSS to make style rules like
<style type="text/css">
#CA,#FL,HI{
fill:blue;
}
#Al, #NY, #NM{
fill:#cc6699;
}
/*etc..*/
</style>
and then you can do a single text replace to inject your css rules into the svg before proceeding with the imagick jpeg/png creation. If the colors don't change, check to make sure you don't have any inline fill styles in your path tags overriding the css.
2) If you don't have to actually create a jpeg/png image file (and don't need to support outdated browsers), you can manipulate the svg directly with jQuery. You can't access the svg paths when embedding the svg using img or object tags, so you'll have to directly include the svg xml in your webpage html like:
<div>
<?php echo file_get_contents('/path/to/blank/us-map.svg');?>
</div>
then changing the colors is as easy as:
<script type="text/javascript" src="/path/to/jquery.js"></script>
<script type="text/javascript">
$('#CA').css('fill', 'blue');
$('#NY').css('fill', '#ff0000');
</script>
When converting SVG to transparent PNG, don't forget to put this BEFORE $imagick->readImageBlob():
$imagick->setBackgroundColor(new ImagickPixel('transparent'));
You mention that you are doing this because IE doesn't support SVG.
The good news is that IE does support vector graphics. Okay, so it's in the form of a language called VML which only IE supports, rather than SVG, but it is there, and you can use it.
Google Maps, among others, will detect the browser capabilities to determine whether to serve SVG or VML.
Then there's the Raphael library, which is a Javascript browswer-based graphics library, which supports either SVG or VML, again depending on the browser.
Another one which may help: SVGWeb.
All of which means that you can support your IE users without having to resort to bitmap graphics.
See also the top answer to this question, for example: XSL Transform SVG to VML
This is v. easy, have been doing work on this for the past few weeks.
You need the Batik SVG Toolkit. Download, and place the files in the same directory as the SVG you want to convert to a JPEG, also make sure you unzip it first.
Open the terminal, and run this command:
java -jar batik-rasterizer.jar -m image/jpeg -q 0.8 NAME_OF_SVG_FILE.svg
That should output a JPEG of the SVG file. Really easy.
You can even just place it in a loop and convert loads of SVGs,
import os
svgs = ('test1.svg', 'test2.svg', 'etc.svg')
for svg in svgs:
os.system('java -jar batik-rasterizer.jar -m image/jpeg -q 0.8 '+str(svg)+'.svg')
This is a method for converting a svg picture to a gif using standard php GD tools
1) You put the image into a canvas element in the browser:
<canvas id=myCanvas></canvas>
<script>
var Key='picturename'
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
base_image = new Image();
base_image.src = myimage.svg;
base_image.onload = function(){
//get the image info as base64 text string
var dataURL = canvas.toDataURL();
//Post the image (dataURL) to the server using jQuery post method
$.post('ProcessPicture.php',{'TheKey':Key,'image': dataURL ,'h': canvas.height,'w':canvas.width,"stemme":stemme } ,function(data,status){ alert(data+' '+status) });
}
</script>
And then convert it at the server (ProcessPicture.php) from (default) png to gif and save it. (you could have saved as png too then use imagepng instead of image gif):
//receive the posted data in php
$pic=$_POST['image'];
$Key=$_POST['TheKey'];
$height=$_POST['h'];
$width=$_POST['w'];
$dir='../gif/'
$gifName=$dir.$Key.'.gif';
$pngName=$dir.$Key.'.png';
//split the generated base64 string before the comma. to remove the 'data:image/png;base64, header created by and get the image data
$data = explode(',', $pic);
$base64img = base64_decode($data[1]);
$dimg=imagecreatefromstring($base64img);
//in order to avoid copying a black figure into a (default) black background you must create a white background
$im_out = ImageCreateTrueColor($width,$height);
$bgfill = imagecolorallocate( $im_out, 255, 255, 255 );
imagefill( $im_out, 0,0, $bgfill );
//Copy the uploaded picture in on the white background
ImageCopyResampled($im_out, $dimg ,0, 0, 0, 0, $width, $height,$width, $height);
//Make the gif and png file
imagegif($im_out, $gifName);
imagepng($im_out, $pngName);
I do not know of a standalone PHP / Apache solution, as this would require a PHP library that can read and render SVG images. I'm not sure such a library exists - I don't know any.
ImageMagick is able to rasterize SVG files, either through the command line or the PHP binding, IMagick, but seems to have a number of quirks and external dependencies as shown e.g. in this forum thread. I think it's still the most promising way to go, it's the first thing I would look into if I were you.
I would like to share my answer too it might help someone.
This it is more for simple case when your svg dose not contain fill style and by default black and you want to convert it to png and add color to result png.
function convertSvgToPng($svgPath, $fillColor, $outPath)
{
$im = new Imagick();
$svg = file_get_contents($svgPath);
// !!! THIS is the trick part - just appending to all <path fill color
$svg = str_replace('<path ', '<path style="fill:'.$fillColor.'" ', $svg);
$im->readImageBlob($svg);
$im->setImageFormat("png24");
$im->writeImage($outPath);
$im->clear();
$im->destroy();
}
You can use Raphaël—JavaScript Library and achieve it easily. It will work in IE also.
$command = 'convert -density 300 ';
if(Input::Post('height')!='' && Input::Post('width')!=''){
$command.='-resize '.Input::Post('width').'x'.Input::Post('height').' ';
}
$command.=$svg.' '.$source;
exec($command);
#unlink($svg);
or using : potrace
demo :Tool4dev.com

Convert SVG image to PNG with PHP

I'm working on a web project that involves a dynamically generated map of the US coloring different states based on a set of data.
This SVG file gives me a good blank map of the US and is very easy to change the color of each state. The difficulty is that IE browsers don't support SVG so in order for me to use the handy syntax the svg offers, I'll need to convert it to a JPG.
Ideally, I'd like to do this with only the GD2 library but could also use ImageMagick. I have absolutely no clue how to do this.
Any solution that would allow me to dynamically change the colors of states on a map of the US will be considered. The key is that it is easy to change the colors on the fly and that it is cross browser. PHP/Apache solutions only, please.
That's funny you asked this, I just did this recently for my work's site and I was thinking I should write a tutorial... Here is how to do it with PHP/Imagick, which uses ImageMagick:
$usmap = '/path/to/blank/us-map.svg';
$im = new Imagick();
$svg = file_get_contents($usmap);
/*loop to color each state as needed, something like*/
$idColorArray = array(
"AL" => "339966"
,"AK" => "0099FF"
...
,"WI" => "FF4B00"
,"WY" => "A3609B"
);
foreach($idColorArray as $state => $color){
//Where $color is a RRGGBB hex value
$svg = preg_replace(
'/id="'.$state.'" style="fill:#([0-9a-f]{6})/'
, 'id="'.$state.'" style="fill:#'.$color
, $svg
);
}
$im->readImageBlob($svg);
/*png settings*/
$im->setImageFormat("png24");
$im->resizeImage(720, 445, imagick::FILTER_LANCZOS, 1); /*Optional, if you need to resize*/
/*jpeg*/
$im->setImageFormat("jpeg");
$im->adaptiveResizeImage(720, 445); /*Optional, if you need to resize*/
$im->writeImage('/path/to/colored/us-map.png');/*(or .jpg)*/
$im->clear();
$im->destroy();
the steps regex color replacement may vary depending on the svg path xml and how you id & color values are stored. If you don't want to store a file on the server, you can output the image as base 64 like
<?php echo '<img src="data:image/jpg;base64,' . base64_encode($im) . '" />';?>
(before you use clear/destroy) but ie has issues with PNG as base64 so you'd probably have to output base64 as jpeg
you can see an example here I did for a former employer's sales territory map:
Start: https://upload.wikimedia.org/wikipedia/commons/1/1a/Blank_US_Map_(states_only).svg
Finish:
Edit
Since writing the above, I've come up with 2 improved techniques:
1) instead of a regex loop to change the fill on state , use CSS to make style rules like
<style type="text/css">
#CA,#FL,HI{
fill:blue;
}
#Al, #NY, #NM{
fill:#cc6699;
}
/*etc..*/
</style>
and then you can do a single text replace to inject your css rules into the svg before proceeding with the imagick jpeg/png creation. If the colors don't change, check to make sure you don't have any inline fill styles in your path tags overriding the css.
2) If you don't have to actually create a jpeg/png image file (and don't need to support outdated browsers), you can manipulate the svg directly with jQuery. You can't access the svg paths when embedding the svg using img or object tags, so you'll have to directly include the svg xml in your webpage html like:
<div>
<?php echo file_get_contents('/path/to/blank/us-map.svg');?>
</div>
then changing the colors is as easy as:
<script type="text/javascript" src="/path/to/jquery.js"></script>
<script type="text/javascript">
$('#CA').css('fill', 'blue');
$('#NY').css('fill', '#ff0000');
</script>
When converting SVG to transparent PNG, don't forget to put this BEFORE $imagick->readImageBlob():
$imagick->setBackgroundColor(new ImagickPixel('transparent'));
You mention that you are doing this because IE doesn't support SVG.
The good news is that IE does support vector graphics. Okay, so it's in the form of a language called VML which only IE supports, rather than SVG, but it is there, and you can use it.
Google Maps, among others, will detect the browser capabilities to determine whether to serve SVG or VML.
Then there's the Raphael library, which is a Javascript browswer-based graphics library, which supports either SVG or VML, again depending on the browser.
Another one which may help: SVGWeb.
All of which means that you can support your IE users without having to resort to bitmap graphics.
See also the top answer to this question, for example: XSL Transform SVG to VML
This is v. easy, have been doing work on this for the past few weeks.
You need the Batik SVG Toolkit. Download, and place the files in the same directory as the SVG you want to convert to a JPEG, also make sure you unzip it first.
Open the terminal, and run this command:
java -jar batik-rasterizer.jar -m image/jpeg -q 0.8 NAME_OF_SVG_FILE.svg
That should output a JPEG of the SVG file. Really easy.
You can even just place it in a loop and convert loads of SVGs,
import os
svgs = ('test1.svg', 'test2.svg', 'etc.svg')
for svg in svgs:
os.system('java -jar batik-rasterizer.jar -m image/jpeg -q 0.8 '+str(svg)+'.svg')
This is a method for converting a svg picture to a gif using standard php GD tools
1) You put the image into a canvas element in the browser:
<canvas id=myCanvas></canvas>
<script>
var Key='picturename'
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
base_image = new Image();
base_image.src = myimage.svg;
base_image.onload = function(){
//get the image info as base64 text string
var dataURL = canvas.toDataURL();
//Post the image (dataURL) to the server using jQuery post method
$.post('ProcessPicture.php',{'TheKey':Key,'image': dataURL ,'h': canvas.height,'w':canvas.width,"stemme":stemme } ,function(data,status){ alert(data+' '+status) });
}
</script>
And then convert it at the server (ProcessPicture.php) from (default) png to gif and save it. (you could have saved as png too then use imagepng instead of image gif):
//receive the posted data in php
$pic=$_POST['image'];
$Key=$_POST['TheKey'];
$height=$_POST['h'];
$width=$_POST['w'];
$dir='../gif/'
$gifName=$dir.$Key.'.gif';
$pngName=$dir.$Key.'.png';
//split the generated base64 string before the comma. to remove the 'data:image/png;base64, header created by and get the image data
$data = explode(',', $pic);
$base64img = base64_decode($data[1]);
$dimg=imagecreatefromstring($base64img);
//in order to avoid copying a black figure into a (default) black background you must create a white background
$im_out = ImageCreateTrueColor($width,$height);
$bgfill = imagecolorallocate( $im_out, 255, 255, 255 );
imagefill( $im_out, 0,0, $bgfill );
//Copy the uploaded picture in on the white background
ImageCopyResampled($im_out, $dimg ,0, 0, 0, 0, $width, $height,$width, $height);
//Make the gif and png file
imagegif($im_out, $gifName);
imagepng($im_out, $pngName);
I do not know of a standalone PHP / Apache solution, as this would require a PHP library that can read and render SVG images. I'm not sure such a library exists - I don't know any.
ImageMagick is able to rasterize SVG files, either through the command line or the PHP binding, IMagick, but seems to have a number of quirks and external dependencies as shown e.g. in this forum thread. I think it's still the most promising way to go, it's the first thing I would look into if I were you.
I would like to share my answer too it might help someone.
This it is more for simple case when your svg dose not contain fill style and by default black and you want to convert it to png and add color to result png.
function convertSvgToPng($svgPath, $fillColor, $outPath)
{
$im = new Imagick();
$svg = file_get_contents($svgPath);
// !!! THIS is the trick part - just appending to all <path fill color
$svg = str_replace('<path ', '<path style="fill:'.$fillColor.'" ', $svg);
$im->readImageBlob($svg);
$im->setImageFormat("png24");
$im->writeImage($outPath);
$im->clear();
$im->destroy();
}
You can use Raphaël—JavaScript Library and achieve it easily. It will work in IE also.
$command = 'convert -density 300 ';
if(Input::Post('height')!='' && Input::Post('width')!=''){
$command.='-resize '.Input::Post('width').'x'.Input::Post('height').' ';
}
$command.=$svg.' '.$source;
exec($command);
#unlink($svg);
or using : potrace
demo :Tool4dev.com

Categories