SVG 文件无处不在——图标、标志、插图、UI 图形...
发布: (2026年2月15日 GMT+8 16:02)
3 分钟阅读
原文: Dev.to
Source: Dev.to
概览
SVG 文件无处不在——图标、标志、插图、UI 图形。它们轻量、可伸缩且适合网页使用,但从设计工具导出的 SVG 往往包含:
- 不必要的元数据
- 冗余属性
- 编辑器特有的痕迹
- 多余的空白
- 可能不安全的元素
如果你在使用 PHP 并且需要一个强大、可配置、具备安全意识的 SVG 优化器,这里有一个专门为此打造的解决方案:
👉 php-svg-optimizer 是一个轻量级的 PHP 库,旨在优化、压缩并清理 SVG 文件,同时遵循 SVG 2.0 规范。
好处
- 更小的文件体积
- 更干净的标记
- 符合标准的 SVG
- 更安全的嵌入
- 输出视觉上保持一致
- 性能提升
安全性
在接受用户上传的 SVG 时,进行消毒不是可选项——它是必需的。
安装
composer require mathiasreker/php-svg-optimizer
用法
1️⃣ 命令行 (CLI)
vendor/bin/svg-optimizer --with-all-rules process /path/to/svgs
2️⃣ 作为 PHP 包使用
try {
$svgOptimizer = (new SvgOptimizer())
->withAllRules()
->optimize()
->saveToFile('path/to/output.svg');
$metaData = $svgOptimizer->getMetaData();
echo sprintf('Optimized size: %d bytes%s', $metaData->getOptimizedSize(), PHP_EOL);
echo sprintf('Original size: %d bytes%s', $metaData->getOriginalSize(), PHP_EOL);
echo sprintf('Size reduction: %d bytes%s', $metaData->getSavedBytes(), PHP_EOL);
echo sprintf('Reduction percentage: %s %%s', $metaData->getSavedPercentage(), PHP_EOL);
echo sprintf('Processing time: %s seconds%s', $metaData->getOptimizationTime(), PHP_EOL);
} catch (\Exception $exception) {
echo $exception->getMessage();
}
配置 – 让它强大的因素
->withRules(
convertColorsToHex: true,
convertCssClassesToAttributes: true,
convertEmptyTagsToSelfClosing: true,
convertInlineStylesToAttributes: true,
fixAttributeNames: false,
flattenGroups: true,
minifySvgCoordinates: true,
minifyTransformations: true,
removeAriaAndRole: true,
removeComments: true,
removeDataAttributes: false,
removeDefaultAttributes: true,
removeDeprecatedAttributes: true,
removeDoctype: true,
removeDuplicateElements: true,
removeEmptyAttributes: true,
removeEmptyGroups: true,
removeEmptyTextElements: true,
removeEnableBackgroundAttribute: false,
removeInkscapeFootprints: true,
removeInvisibleCharacters: true,
removeMetadata: true,
removeNonStandardAttributes: false,
removeNonStandardTags: false,
removeTitleAndDesc: true,
removeUnnecessaryWhitespace: true,
removeUnsafeElements: false,
removeUnusedMasks: true,
removeUnusedNamespaces: true,
removeWidthHeightAttributes: false,
sortAttributes: true,
)
安全的 SVG 上传示例
SvgOptimizerFacade::fromFile('uploaded.svg')
->withRules(
removeUnsafeElements: true,
removeNonStandardTags: true,
removeNonStandardAttributes: true
)
->allowRisky()
->optimize()
->saveToFile('sanitized.svg');
这可以显著降低在嵌入用户上传的 SVG 时出现 XSS 的风险。
开发者体验
该项目强调:
- PHPStan Level 9
- 100 % 类型覆盖率
- 高测试覆盖率
- 基于策略的架构
- 确定性的输出
如果你在 PHP 中处理 SVG,这个工具值得加入你的工作流。
⭐ 如果你觉得它有用,请考虑在 GitHub 上给它点个星。