yoya/php-svg

使用PHP(yoya的定制)读取、编辑、写入和渲染SVG文件

v1.0.0 2018-05-31 15:34 UTC

This package is auto-updated.

Last update: 2024-09-07 01:13:03 UTC


README

这是一个PHP的矢量图形库,其规范非常广泛。这是因为该项目的目标是提供三个不同、大型领域的功能

  • 从PHP代码生成SVG图像,并将它们输出为XML字符串或文件。
  • 加载和解析XML字符串到文档树,这些文档树可以轻松修改,然后再将它们转换回字符串。
  • 将解析或生成的文档树转换为位图图形,如PNG。

贡献

这些任务将花费很多时间和精力,如果您对这个项目感兴趣,欢迎您贡献。
如果您决定贡献,请遵守以下事项

  1. 不得使用外部库。
  2. 请将您的编辑器设置为使用4个空格进行缩进。一般来说,遵循现有的代码风格会更一致。
  3. 源文件必须以换行符结尾。
  4. 通过贡献代码,您同意将代码许可给本项目,许可协议为MIT许可。

安装

Composer(推荐)

此软件包通过Composer/Packagist提供

$ composer require yoya/php-svg

手册

下载此存储库或最新版本,并将其放置在项目中的某个位置。然后执行

<?php
require_once __DIR__.'/<path_where_you_put_it>/autoloader.php';

其余步骤与使用Composer完全相同,只是没有良好的版本管理功能。

入门

创建图像

以下代码生成一个带有蓝色正方形的SVG,设置Content-Type头并输出它

<?php

use SVG\SVGImage;
use SVG\Nodes\Shapes\SVGRect;

// image with 100x100 viewport
$image = new SVGImage(100, 100);
$doc = $image->getDocument();

// blue 40x40 square at (0, 0)
$square = new SVGRect(0, 0, 40, 40);
$square->setStyle('fill', '#0000FF');
$doc->addChild($square);

header('Content-Type: image/svg+xml');
echo $image;

光栅化

要将SVGImage实例转换为PHP/GD图像资源,换句话说,将其转换为位图图像,您只需在它上调用toRasterImage($width, $height)即可。示例

<?php

use SVG\SVGImage;
use SVG\Nodes\Shapes\SVGCircle;

$image = new SVGImage(100, 100);
$doc = $image->getDocument();

// circle with radius 20 and green border, center at (50, 50)
$doc->addChild(
    (new SVGCircle(50, 50, 20))
        ->setStyle('fill', 'none')
        ->setStyle('stroke', '#0F0')
        ->setStyle('stroke-width', '2px')
);

// rasterize to a 200x200 image, i.e. the original SVG size scaled by 2
$rasterImage = $image->toRasterImage(200, 200);

header('Content-Type: image/png');
imagepng($rasterImage);

加载SVG

您可以从字符串和文件加载SVG图像。此示例从一个字符串加载,移动包含的矩形,并输出新的SVG

<?php

use SVG\SVGImage;

$svg  = '<svg width="100" height="100">';
$svg .= '<rect width="50" height="50" fill="#00F" />';
$svg .= '</svg>';

$image = SVGImage::fromString($svg);
$doc = $image->getDocument();

$rect = $doc->getChild(0);
$rect->setX(25)->setY(25);

header('Content-Type: image/svg+xml');
echo $image;

如果您想从文件加载,您将调用SVGImage::fromFile($file)。该函数支持本地文件路径以及URL。