Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@FirePanther
Created October 5, 2020 21:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save FirePanther/aa704a1965d2588aed0e4258b6cce04d to your computer and use it in GitHub Desktop.
Save FirePanther/aa704a1965d2588aed0e4258b6cce04d to your computer and use it in GitHub Desktop.
<?php
$settings = [];
// svg file
if (isset($_GET['svg'])) {
// general/custom svg file
$svgFile = DIR_ASSETS.'/cdn/dist/svg/'.$_GET['svg'];
if (!preg_match('~^\w[\w/-]+\.svg$~', $_GET['svg']) || !file_exists($svgFile)) die('Invalid svg');
} elseif (isset($_GET['fa'])) {
// fontawesome icon
$types = [
'b' => 'brands',
'd' => 'duotone',
'l' => 'light',
'r' => 'regular',
's' => 'solid'
];
$type = $types['s'];
if (isset($_GET['type']) && isset($types[$_GET['type'][0]])) $type = $types[$_GET['type'][0]];
$svgFile = DIR_ASSETS.'/cdn/dist/svg/fontawesome/'.$type.'/'.$_GET['fa'].'.svg';
if (!preg_match('~^[\w-]+$~', $_GET['fa']) || !file_exists($svgFile)) die('Invalid fontawesome icon');
} else {
// invalid
die('Unknown SVG');
}
$settings['svg'] = $svgFile;
// set path color
if (isset($_GET['color']) && preg_match('~^\#?[a-f0-9]{6}$~i', $_GET['color'])) {
$tmp = 'image-converter/svg/'.md5($svgFile);
$svg = file_get_contents($svgFile);
$color = ($_GET['color'][0] !== '#' ? '#' : '').$_GET['color'];
$settings['color'] = $color;
$svg = preg_replace_callback('~<path[^>]*>~', function($m) use ($color) {
if (preg_match('~\s+fill="(.*?)"~', $m[0], $pm)) {
return str_replace($pm[0], ' fill="'.$color.'"', $m[0]);
} else {
return '<path fill="'.$color.'"'.substr($m[0], 5);
}
}, $svg);
Tmp::set($tmp, $svg);
$svgFile = DIR_LIB.'/data/tmp/'.$tmp.'.data';
}
// dimensions
$width = false; $height = false;
// force same width and height (not proportional)
if (isset($_GET['size'])) {
$_GET['width'] = $_GET['size'];
$_GET['height'] = $_GET['size'];
}
// set specific dimensions (setting only one is proportional)
if (isset($_GET['width']) && $_GET['width'] > 0 && $_GET['width'] <= 1024) $width = +$_GET['width'];
if (isset($_GET['height']) && $_GET['height'] > 0 && $_GET['height'] <= 1024) $height = +$_GET['height'];
$settings['width'] = $width;
$settings['height'] = $height;
// cache path
$tmpPath = DIR_LIB.'/data/tmp/image-converter/svg-converted/'.md5(json_encode($settings)).'.png';
if (!is_dir(dirname($tmpPath))) @mkdir(dirname($tmpPath), 0777, true);
if (!file_exists($tmpPath) || filemtime($tmpPath) <= filemtime(__FILE__)) {
// recache
$command = 'inkscape'.($width ? ' -w '.$width : '').($height ? ' -h '.$height : '').' "'.$svgFile.'" -e "'.$tmpPath.'"';
exec($command);
}
// show image
header('Content-Type: image/png');
readfile($tmpPath);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment