Rectangle 27 0

Convert SVG image to PNG with PHP?


I'm using it in my project and actually converts the SVG into PNG (with the help of PHP to save the file of course)

you could use canvg js library to convert the SVG into PNG, more info here http://paksula.users.cs.helsinki.fi/svg_open_2010/demo.xhtml compatible with all major browsers!

Note
Rectangle 27 0

Convert SVG image to PNG with PHP?


$dom = new DOMDocument(); $dom->loadXML( $svg ); $dom->getElementsByTagName('image')->item(0)->setAttribute('id', $state); $svg = $dom->saveXML();
$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();
<?php echo '<img src="data:image/jpg;base64,' . base64_encode($im) . '"  />';?>
<div>
<?php echo file_get_contents('/path/to/blank/us-map.svg');?>
</div>
<script type="text/javascript" src="/path/to/jquery.js"></script>
<script type="text/javascript">
    $('#CA').css('fill', 'blue');
    $('#NY').css('fill', '#ff0000');
</script>
<style type="text/css">
#CA,#FL,HI{
    fill:blue;
}
#Al, #NY, #NM{
    fill:#cc6699;
}
/*etc..*/
</style>

(before you use clear/destroy) but ie has issues with PNG as base64 so you'd probably have to output base64 as jpeg

1) instead of a regex loop to change the fill on state , use CSS to make style rules like

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:

SVG is not supported in ie8 or lower without requiring the user to install an svg viewer plugin - from SVG Wikipedia page: "All major modern web browsers, support and render SVG markup directly with the very notable exception of Microsoft Internet Explorer (IE)[3] The Internet Explorer 9 beta supports the basic SVG feature set.[4] Currently, support for browsers running under Android is also limited."

Since writing the above, I've come up with 2 improved techniques:

Thanks for the very exact and useful tutorial on how to do this. I'll certainly use your solution as a backup but am eager to try and just get svg compatibility across all major browsers.

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 ImageMagick:

Yes, but svgweb seems to iron out all the incompatibilities using a little bit of js and flash. That's the solution I went with.

an xml parser would be a safer, albeit slightly slower, solution with any other svg... in this case the regex is safe because I made sure each state's attributes were formatted exactly as (id="XX" style="fill:#XXXXXX").

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.

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

then changing the colors is as easy as:

you can see an example here I did for a former employer's sales territory map:

Note
Rectangle 27 0

Convert SVG image to PNG with PHP?


$dom = new DOMDocument(); $dom->loadXML( $svg ); $dom->getElementsByTagName('image')->item(0)->setAttribute('id', $state); $svg = $dom->saveXML();
$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();
<?php echo '<img src="data:image/jpg;base64,' . base64_encode($im) . '"  />';?>
<div>
<?php echo file_get_contents('/path/to/blank/us-map.svg');?>
</div>
<script type="text/javascript" src="/path/to/jquery.js"></script>
<script type="text/javascript">
    $('#CA').css('fill', 'blue');
    $('#NY').css('fill', '#ff0000');
</script>
<style type="text/css">
#CA,#FL,HI{
    fill:blue;
}
#Al, #NY, #NM{
    fill:#cc6699;
}
/*etc..*/
</style>

(before you use clear/destroy) but ie has issues with PNG as base64 so you'd probably have to output base64 as jpeg

1) instead of a regex loop to change the fill on state , use CSS to make style rules like

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:

SVG is not supported in ie8 or lower without requiring the user to install an svg viewer plugin - from SVG Wikipedia page: "All major modern web browsers, support and render SVG markup directly with the very notable exception of Microsoft Internet Explorer (IE)[3] The Internet Explorer 9 beta supports the basic SVG feature set.[4] Currently, support for browsers running under Android is also limited."

Since writing the above, I've come up with 2 improved techniques:

Thanks for the very exact and useful tutorial on how to do this. I'll certainly use your solution as a backup but am eager to try and just get svg compatibility across all major browsers.

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 ImageMagick:

Yes, but svgweb seems to iron out all the incompatibilities using a little bit of js and flash. That's the solution I went with.

an xml parser would be a safer, albeit slightly slower, solution with any other svg... in this case the regex is safe because I made sure each state's attributes were formatted exactly as (id="XX" style="fill:#XXXXXX").

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.

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

then changing the colors is as easy as:

you can see an example here I did for a former employer's sales territory map:

Note
Rectangle 27 0

Convert SVG image to PNG with PHP?


After testing Batik, Imagemagick and some web based solutions, phantomjs was the only way to get right the following: clipping, masking, filter effects, foreignObject (and even the html-content that was laid in front of svg). Really can recommend this!

Another very fast & accurate option is the headless browser PhantomJS (webkit)

Note
Rectangle 27 0

Convert SVG image to PNG with PHP?


+1 This would be the simple and best answer.

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.

Note
Rectangle 27 0

Convert SVG image to PNG with PHP?


I'm using it in my project and actually converts the SVG into PNG (with the help of PHP to save the file of course)

you could use canvg js library to convert the SVG into PNG, more info here http://paksula.users.cs.helsinki.fi/svg_open_2010/demo.xhtml compatible with all major browsers!

Note
Rectangle 27 0

Convert SVG image to PNG with PHP?


$imagick->setBackgroundColor(new ImagickPixel('transparent'));
Note
Rectangle 27 0

Convert SVG image to PNG with PHP?


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')
java -jar batik-rasterizer.jar -m image/jpeg -q 0.8 NAME_OF_SVG_FILE.svg

place the files in the same directory as the SVG you want to convert to a JPEG

Open the terminal, and run this command:

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,

This is great. Thanks for the tip. I'm going to use it in conjunction with perl to batch-process loads of SVG files I created from a template.

This is v. easy, have been doing work on this for the past few weeks.

Note
Rectangle 27 0

Convert SVG image to PNG with PHP?


$dom = new DOMDocument(); $dom->loadXML( $svg ); $dom->getElementsByTagName('image')->item(0)->setAttribute('id', $state); $svg = $dom->saveXML();
$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();
<?php echo '<img src="data:image/jpg;base64,' . base64_encode($im) . '"  />';?>
<div>
<?php echo file_get_contents('/path/to/blank/us-map.svg');?>
</div>
<script type="text/javascript" src="/path/to/jquery.js"></script>
<script type="text/javascript">
    $('#CA').css('fill', 'blue');
    $('#NY').css('fill', '#ff0000');
</script>
<style type="text/css">
#CA,#FL,HI{
    fill:blue;
}
#Al, #NY, #NM{
    fill:#cc6699;
}
/*etc..*/
</style>

(before you use clear/destroy) but ie has issues with PNG as base64 so you'd probably have to output base64 as jpeg

1) instead of a regex loop to change the fill on state , use CSS to make style rules like

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:

SVG is not supported in ie8 or lower without requiring the user to install an svg viewer plugin - from SVG Wikipedia page: "All major modern web browsers, support and render SVG markup directly with the very notable exception of Microsoft Internet Explorer (IE)[3] The Internet Explorer 9 beta supports the basic SVG feature set.[4] Currently, support for browsers running under Android is also limited."

Since writing the above, I've come up with 2 improved techniques:

Thanks for the very exact and useful tutorial on how to do this. I'll certainly use your solution as a backup but am eager to try and just get svg compatibility across all major browsers.

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 ImageMagick:

Yes, but svgweb seems to iron out all the incompatibilities using a little bit of js and flash. That's the solution I went with.

an xml parser would be a safer, albeit slightly slower, solution with any other svg... in this case the regex is safe because I made sure each state's attributes were formatted exactly as (id="XX" style="fill:#XXXXXX").

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.

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

then changing the colors is as easy as:

you can see an example here I did for a former employer's sales territory map:

Note
Rectangle 27 0

Convert SVG image to PNG with PHP?


+1 for mentioning raphael, which is definitely a good solution and worth investigating for its excellent implementation of cross browser vector graphics.

All of which means that you can support your IE users without having to resort to bitmap graphics.

Google Maps, among others, will detect the browser capabilities to determine whether to serve SVG or VML.

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.

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.

You mention that you are doing this because IE doesn't support SVG.

Note