博客园  :: 首页  :: 新随笔  :: 订阅 订阅  :: 管理

PHP 动态输出 svgz 格式图片

Posted on 2019-10-22 16:52  PHP-张工  阅读(548)  评论(0编辑  收藏  举报

使用PHP动态生成SVGZ图片(gzip压缩的SVG)

经测试SVG的动画性能很差,简单的动画CPU都能占到 30%左右。

可能的用途:

  • 动态天气图片
  • 访问统计计数图片
  • 文字验证生成
  • 动态头像
  • 静态外连图片
  • 图片CHART
<?php

header('Content-Type:image/svg+xml'); 
header('Content-Encoding:gzip'); 

$image_width = @$_GET['w'] ?: 800;
$image_height = @$_GET['h'] ?: 600;

$svg = <<<EOF
<svg version="1.1"
 width="{$image_width}"
 height="{$image_height}"
 viewBox="0 0 {$image_width} {$image_height}"
 preserveAspectRatio="none"
 xmlns="http://www.w3.org/2000/svg"
 xmlns:xlink="http://www.w3.org/1999/xlink"
>

<defs>
<g id="E" transform="translate(-340,-90)">
    <circle cx="340" cy="90" r="15" fill="blue" />
    <path id="path2" d="M390,80 h 0 a50,19 0 1,0 1,1 z" fill="none" stroke="white" stroke-width="1"/>
    <circle cx="0" cy="0" r="5" fill="white" stroke="black" stroke-width="1" >
           <animateMotion dur="30s" repeatCount="indefinite">
            <mpath xlink:href="#path2" />
        </animateMotion>
    </circle>
</g>
<radialGradient id="sunfill" cx="50%" cy="50%" r="100%">
    <stop stop-color="#FF0000" offset="0%" stop-opacity="1"/>
    <stop stop-color="#FBF900" offset="95%" stop-opacity="1"/>
    <stop stop-color="#FFFFFF" offset="100%" stop-opacity="1"/>
</radialGradient>
</defs>

<rect x="0" y="0" width="100%" height="100%" fill="black" />

<circle cx="50%" cy="50%" r="10%" fill="url(#sunfill)" />
<path id="path1" d="M700,200 h 0 a350,200 0 1,0 1,1 z" fill="none" stroke="white" stroke-width="1"/>

<use x="0" y="0" xlink:href="#E">
<animateMotion dur="365s" repeatCount="indefinite" >
    <mpath xlink:href="#path1" />
</animateMotion>
</use>

EOF;

$err = 'svg 生成错误!' . $_SERVER['REMOTE_ADDR'] . $_SERVER['HTTP_USER_AGENT'];

if ($err != '')
{
    $svg .= '<text x="10" y="20" font-size="12" text-anchor="start" fill="#f00">' . $err . '</text>';
}

$svg .= '</svg>';

$svg = gzencode($svg, 9);

echo $svg;