Converting an Image to standalone SVG

Abstract

SVG offers the possibility to display images within an SVG viewer by either referencing to the image file or – wich makes the SVG file standalone – embeding the image source within the SVG file [1]. To have a standalone file one needs to encde the image by base64 [2]. The code below is reading the test.jpg file binary safe, which is one of the important parts here, while it is later converted directly by the PHP built-in base64_encode()function [3].
Finally the encoded string and the image size parameters will be applied to an SVG template file. Have a look at the sample script too [4].

Happy SVGin!

Script: image2svg.php

<?php
/**
* Topic: Converting an image to standalone SVG
* Author: Urs Gehrig
* Date: 2002-04-22
* License: GNU General Public License (GPL)
* http://www.gnu.org/licenses/gpl.html
*
* Thanks: Vincent Hardy
*/

// One never knows, how long it will last…
ini_set(\”max_execution_time\”, 10000);

// Get them from cvs.php.net
require_once(\”HTML/ITX.php\” );

// Load a test image
$filename = \”test.jpg\”;
$fd = fopen ($filename, \”rb\” ) or
die (\”File $file cannot be opened.\” );

// Read binary-safe
$buffer = fread($fd, filesize ($filename) );
fclose ($fd);

// Get parameters of the image
$par = getimagesize($filename );

// Handle the template file
$tpl = new IntegratedTemplate(\”.\” );
$tpl->loadTemplatefile(\”tpl.image.svg\”, true, true);
$content = array
(
\”img_information\” => base64_encode($buffer ),
\”img_width\” => $par[0],
\”img_height\” => $par[1],
\”script_name\” => basename($SCRIPT_NAME)
);
$tpl->setVariable($content);

// Ouput the SVG file
header(\”Content-type: image/svg+xml\”);
$tpl->show();
?>

Script: tpl.image.svg

<?xml version=\”1.0\” encoding=\”iso-8859-1\” ?>
<!–
// *****************************************
// Image To SVG Conversion
// Copyright (c) 2002, 2003 by Urs Gehrig
// *****************************************
//–>
<svg width=\”{img_width}\” height=\”{img_height}\”
viewBox=\”0 0 {img_width} {img_height}\”
xml:space=\”preserve\”>

<g id=\”image_1\”>
<image width=\”{img_width}\” height=\”{img_height}\”
xlink:href=\”data:image/jpeg;base64,{img_information}\”
transform=\”matrix(1 0 0 1 0 0)\”/>
</g>

<a xlink:href=\”{script_name}\” target=\”_self\”>
<text style=\”font-size:10; stroke:black; stroke-width:0.5\” x=\”5\” y=\”12\”>circle.ch</text></a>
</svg>

Links

[1] http://www.w3.org/Graphics/SVG/ – Scalable Vector Graphics (SVG)
[2] http://www.ietf.org/rfc/rfc2045.txt – Multipurpose Internet Mail Extensions (MIME)
[3] http://www.php.net/base64_encode – Base 64 encoding
[4] http://circle.ch/projects/image2svg/ – Convert your Image online

Leave a Reply