You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

编写PHP脚本将SVG中图片路径转为Base64的需求咨询

PHP脚本自动把SVG里的图片转成Base64内联

我写了个PHP脚本,能自动扫描Adobe Animate导出的SVG里的img/路径,把图片转成Base64编码替换进去,生成不用依赖外部图片的独立SVG文件。

核心逻辑

  • 读入SVG文件内容
  • 正则匹配所有<image>标签里的xlink:href="img/..."路径
  • 逐个读取对应图片文件,转成带MIME类型的Base64字符串
  • 替换SVG里的原始路径,最后保存新文件

完整脚本

<?php
// 输入SVG文件路径
$inputSvgPath = 'input.svg';
// 输出处理后的SVG文件路径
$outputSvgPath = 'output.svg';

// 检查输入文件是否存在
if (!file_exists($inputSvgPath)) {
    die("错误:输入SVG文件不存在");
}

// 读取SVG内容
$svgContent = file_get_contents($inputSvgPath);

// 正则匹配所有image标签的xlink:href属性(匹配img/开头的路径)
$pattern = '/xlink:href="img\/([^"]+)"/';
preg_match_all($pattern, $svgContent, $matches);

if (!empty($matches[1])) {
    foreach ($matches[1] as $index => $imageFileName) {
        $imagePath = 'img/' . $imageFileName;
        
        // 检查图片文件是否存在
        if (!file_exists($imagePath)) {
            echo "警告:图片文件 {$imagePath} 不存在,跳过替换\n";
            continue;
        }
        
        // 获取图片MIME类型
        $mime = mime_content_type($imagePath);
        if (!$mime) {
            echo "警告:无法识别图片 {$imagePath} 的MIME类型,跳过替换\n";
            continue;
        }
        
        // 读取图片内容并转Base64
        $imageData = base64_encode(file_get_contents($imagePath));
        $base64Url = "data:{$mime};base64,{$imageData}";
        
        // 替换SVG中的原始路径
        $svgContent = str_replace($matches[0][$index], "xlink:href=\"{$base64Url}\"", $svgContent);
    }
}

// 保存处理后的SVG
if (file_put_contents($outputSvgPath, $svgContent)) {
    echo "处理完成!已生成文件:{$outputSvgPath}\n";
} else {
    die("错误:无法保存输出文件");
}
?>

使用方法

  1. 把这个脚本放到你的SVG文件所在目录,确保img/文件夹和脚本在同一层级(就是Adobe Animate导出时生成的图片文件夹)
  2. 修改脚本里的$inputSvgPath为你的原始SVG文件名,$outputSvgPath为你想要生成的新文件名
  3. 运行这个PHP脚本(可以用命令行php svg-inline-images.php,或者放到Web服务器上访问)

测试效果

拿你给的示例SVG来说,处理前的<image>标签是:

<image overflow="visible" xlink:href="img/myimage.png" height="128" width="600"/>

处理后会变成:

<image overflow="visible" xlink:href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA...(省略Base64内容)" height="128" width="600"/>

内容的提问来源于stack exchange,提问作者spanakorizo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 20:52:02