我正在使用一个软件(adobe animate),该软件将导出动画 .svg 文件,并在导出的 .svg 文件上写入图像路径。然后我需要手动将它们转换为base64,并再次手动将每个
<image xlink:href="">
替换为编码的.png图像的base64字符串。我正在考虑编写一个 php 脚本,该脚本将扫描 .svg 文档中存储这些图像的路径 /img,并将 .svg 文件中的每个路径替换为 base64,因此最后一个文件将包含所有内联图像。有任何想法吗?我还发布了一个非常简单的 .svg 文件示例,该文件仅包含一张图像,它基本上是 html 代码。
<?xml version="1.0" encoding="utf-8"?><svg id="RECOVER_Untitled-7_2023123103220" image-rendering="auto" baseProfile="basic" version="1.1" x="0px" y="0px" width="400" height="300" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><g id="Scene-1-copy-1" overflow="visible"><g id="Symbol-1" transform="translate(0 86)"><animateTransform attributeName="transform" additive="replace" type="translate" repeatCount="indefinite" dur="1s" keyTimes="0;.04199;.042;.08299;.083;.12499;.125;.16699;.167;.20799;.208;.24999;.25;.29199;.292;.33299;.333;.37499;.375;.41699;.417;.45799;.458;.49999;.5;.54199;.542;.58299;.583;.62499;.625;.66699;.667;.70799;.708;.74999;.75;.79199;.792;.83299;.833;.87499;.875;.91699;.917;.95799;.958;1" values="0,86;0,86;-8.65,90.55;-8.65,90.55;-17.35,95.1;-17.35,95.1;-26.05,99.65;-26.05,99.65;-34.75,104.25;-34.75,104.25;-43.45,108.8;-43.45,108.8;-52.15,113.35;-52.15,113.35;-60.85,117.9;-60.85,117.9;-69.55,122.5;-69.55,122.5;-78.25,127.05;-78.25,127.05;-86.95,131.6;-86.95,131.6;-95.65,136.15;-95.65,136.15;-104.3,140.75;-104.3,140.75;-113,145.3;-113,145.3;-121.7,149.85;-121.7,149.85;-130.4,154.4;-130.4,154.4;-139.1,159;-139.1,159;-147.8,163.55;-147.8,163.55;-156.5,168.1;-156.5,168.1;-165.2,172.65;-165.2,172.65;-173.9,177.25;-173.9,177.25;-182.6,181.8;-182.6,181.8;-191.3,186.35;-191.3,186.35;-200,190.95;-200,190.95" calcMode="discrete"/><image overflow="visible" xlink:href="img/myimage.png" height="128" width="600"/></g></g></svg>
<?php
function convertImagesToBase64($svgFilePath) {
// Read the SVG file content
$svgContent = file_get_contents($svgFilePath);
// Regular expression to find image paths
$pattern = '/xlink:href="([^"]+)"/i';
// Function to convert image to base64
$convertToBase64 = function ($matches) {
$imagePath = $matches[1];
$imageType = pathinfo($imagePath, PATHINFO_EXTENSION);
$imageData = file_get_contents($imagePath);
$base64 = 'data:image/' . $imageType . ';base64,' . base64_encode($imageData);
return 'xlink:href="' . $base64 . '"';
};
// Replace image paths with base64 strings
$svgContent = preg_replace_callback($pattern, $convertToBase64, $svgContent);
// Return the modified SVG content
return $svgContent;
}
// Path to your SVG file
$svgFilePath = 'path/to/your/svgfile.svg';
// Convert and get the modified SVG content
$modifiedSvgContent = convertImagesToBase64($svgFilePath);
// Optionally, save the modified SVG content to a new file
file_put_contents('path/to/modified_svgfile.svg', $modifiedSvgContent);
echo "Conversion completed.";
?>