atelier/svg
Composer 安装命令:
composer require atelier/svg
包简介
PHP library for SVG manipulation, optimization, and morphing: parsing, building, styling, transforms, validation, and sanitization
关键字:
README 文档
README
The SVG toolkit for PHP.
A PHP library for SVG manipulation, optimization, and morphing. Parse, build, style, transform, validate, sanitize, and animate SVG graphics with a type-safe, fluent API.
Quick Start | Features | Use Cases | Documentation
Installation
composer require atelier/svg
Requires PHP 8.3+.
Quick Start
use Atelier\Svg\Svg; Svg::create(300, 200) ->rect(0, 0, 300, 200, ['fill' => '#1e293b']) ->circle(150, 100, 60, ['fill' => '#3b82f6']) ->text(150, 180, 'Atelier SVG', ['text-anchor' => 'middle', 'fill' => '#fff']) ->optimize() ->save('output.svg');
Load, query, modify, save:
$svg = Svg::load('input.svg'); $svg->getDocument() ->querySelectorAll('circle') ->fill('#3b82f6') ->stroke('#000') ->strokeWidth(2); $svg->optimize()->save('output.svg');
Features
Elements
Full SVG 1.1 element support: shapes, text, groups, symbols, markers, gradients, filters, clipping, masking, and animation: all as typed PHP classes.
$text = TextElement::create(10, 30, 'Hello'); $builder = new TspanBuilder($text); $builder->add('Bold', 0, ['font-weight' => 'bold']) ->add('and italic', 10, ['font-style' => 'italic']);
$symbol = SymbolBuilder::createSymbol($document, 'icon-star', '0 0 24 24'); SymbolBuilder::useSymbol($document, 'icon-star', 10, 10); $marker = MarkerBuilder::arrow($document, 'arrow-end', '#000', 10);
AnimationBuilder::fadeIn($element, '1s'); AnimationBuilder::rotate($element, 0, 360, '2s');
Elements documentation: Shapes, text, structural elements, selectors, accessibility
Filters & Effects
26+ filter primitives, linear and radial gradients, patterns, clipping, and masking: with fluent builders.
FilterBuilder::createDropShadow($document, 'shadow', 2, 2, 4, '#000', 0.3); FilterBuilder::create($document, 'glow') ->gaussianBlur(3, 'SourceAlpha', 'blur') ->flood('#3b82f6', 0.8, 'color') ->composite('in', 'color', 'blur', 'glow') ->blend('normal', 'SourceGraphic', 'glow') ->addToDefs();
GradientBuilder::horizontal($document, 'sunset', '#ff6b6b', '#feca57'); GradientBuilder::createLinear($document, 'custom') ->from(0, 0)->to(100, 100) ->addStop(0, '#3b82f6') ->addStop(50, '#8b5cf6', 0.8) ->addStop(100, '#ec4899') ->addToDefs();
Filters documentation: Gradients: Clipping & Masking
Paths
Type-safe path building, geometric analysis, distance metrics, and simplification.
$data = PathBuilder::startAt(10, 10) ->lineTo(50, 50) ->curveTo(250, 50, 300, 50, 350, 100) ->arcTo(50, 50, 0, false, true, 500, 100) ->closePath() ->toData(); $analyzer = new PathAnalyzer($data); $length = $analyzer->getLength(); $bbox = $analyzer->getBoundingBox(); $inside = $analyzer->containsPoint(new Point(25, 25));
Path documentation: Building, analysis, transforms, simplification
Optimization
A configurable pipeline with 40+ passes, inspired by SVGO. Four presets, or build your own.
Svg::load('input.svg')->optimize()->save('output.svg');
Before:
<svg width="100.00000" height="100.00000" viewBox="0.00 0.00 100.00 100.00"> <rect x="10.00000" y="20.00000" width="80.00000" height="60.00000" fill="black" stroke="none" opacity="1.0" /> </svg>
After:
<svg width="100" height="100" viewBox="0 0 100 100"> <rect x="10" y="20" width="80" height="60" fill="#000"/> </svg>
$optimizer = new Optimizer(OptimizerPresets::default()); // Balanced $optimizer = new Optimizer(OptimizerPresets::aggressive()); // Maximum reduction $optimizer = new Optimizer(OptimizerPresets::safe()); // Conservative $optimizer = new Optimizer(OptimizerPresets::web()); // Production delivery
Optimization documentation: Passes, presets, custom pipelines
Security & Validation
Sanitize untrusted SVGs, validate against the spec, check accessibility.
Sanitizer::strict()->sanitize($document); // Remove scripts, event handlers, JS URLs Sanitizer::default()->sanitize($document); // Balanced security
$validator = new Validator(ValidationProfile::strict()); $result = $validator->validate($document); $broken = DocumentValidator::findBrokenReferences($document); DocumentValidator::autoFix($document);
$issues = Accessibility::checkAccessibility($document); Accessibility::setTitle($document, 'Sales Chart Q1 2025'); Accessibility::improveAccessibility($document);
Validation documentation: Sanitization: Accessibility
Morphing
Interpolate between SVG shapes with easing. Export to SMIL, CSS keyframes, or JavaScript.
$midPath = Morph::between($startPath, $endPath, 0.5); $frames = Morph::create() ->from($startPath) ->to($endPath) ->withDuration(2000, 60) ->withEasing('ease-in-out') ->generate(); $doc = AnimationExporter::toAnimatedSVG($frames, ['duration' => 3]); $css = AnimationExporter::toCSSKeyframes($frames, 'my-morph');
Morphing documentation: Interpolation, easing, exporting
Use Cases
Sanitize user-uploaded SVGs
Accept SVGs from users without risking XSS. Strip scripts and dangerous content, validate structure, optimize, and serve.
$svg = Svg::load($uploadedFile); $document = $svg->getDocument(); Sanitizer::strict()->sanitize($document); DocumentValidator::autoFix($document); $svg->optimize()->save($outputPath);
Generate icon sprite sheets
Consolidate individual icon files into a single SVG sprite for fewer HTTP requests.
$icons = array_map(fn ($file) => Svg::load($file)->getDocument(), glob('icons/*.svg')); $sprite = Document::merge($icons, ['strategy' => MergeStrategy::SYMBOLS]);
<svg><use href="sprite.svg#icon-home"/></svg>
Batch-process SVG assets
Optimize an entire directory of SVGs in a CI pipeline or build step.
$optimizer = new Optimizer(OptimizerPresets::aggressive()); foreach (glob('assets/svg/*.svg') as $file) { $document = (new DomLoader())->loadFromFile($file); $optimizer->optimize($document); (new CompactXmlDumper())->dumpToFile($document, $file); }
Build charts and dashboards
Compose SVG documents programmatically: generate charts, combine them into layouts, add accessible metadata.
$chart = Svg::create(400, 300); foreach ($data as $i => $value) { $height = $value * 2; $chart->rect($i * 50 + 10, 300 - $height, 40, $height, ['fill' => '#3b82f6']); } Accessibility::setTitle($chart->getDocument(), 'Monthly Revenue'); Accessibility::setDescription($chart->getDocument(), 'Bar chart showing revenue by month'); $chart->save('chart.svg');
Animate shape transitions
Morph between two SVG shapes and export as a self-contained animated SVG.
$star = Svg::load('star.svg')->getDocument()->querySelector('path'); $circle = Svg::load('circle.svg')->getDocument()->querySelector('path'); $frames = Morph::frames( Path::parse($star->getAttribute('d'))->getData(), Path::parse($circle->getAttribute('d'))->getData(), 60, 'ease-in-out', ); $animated = AnimationExporter::toAnimatedSVG($frames, [ 'duration' => 2, 'repeatCount' => 'indefinite', ]);
Documentation
- Installation: Requirements and setup
- Quick Start: Create, load, manipulate SVGs
- Document Handling: Creating, loading, exporting, sanitization, validation
- Elements: Shapes, text, animation, selectors, gradients, filters, clipping
- Path Operations: Building, analysis, transforms, geometry, simplification
- Styling: Layout, transforms, and values
- Optimization: Passes and presets
- Morphing: Interpolation, easing, exporting
- Guides: Sanitization, batch processing, charts, animation
Contributing
Contributions are welcome! See CONTRIBUTING.md for guidelines.
License
Atelier SVG is open-source software licensed under the MIT License.
atelier/svg 适用场景与选型建议
atelier/svg 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 28 次下载、GitHub Stars 达 3, 最近一次更新时间为 2026 年 04 月 06 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「path」 「parser」 「validation」 「filter」 「transform」 「optimization」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 atelier/svg 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 atelier/svg 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 atelier/svg 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
Easy to use SDK with grabber for multiple platforms at once like YouTube, Dailymotion, Facebook and more.
JSONPath implementation for querying and updating JSON objects with support for json flattening into a table
An MT940 bank statement parser for PHP
The InstantConfigurationCopy module provides easy way to copy configuration field information for admin in back office Magento 2.
Adds request-parameter validation to the SLIM 3.x PHP framework
Laravel integration for the jsonapi.org parser
统计信息
- 总下载量: 28
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 3
- 点击次数: 36
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2026-04-06