php, svg文件转png图片实现
环境安装:
php的swoole4.8扩展、imagick软件(已安装)、php的imagick扩展(已安装)、
设置php.ini:
grpc.enable_fork_support = 1
swoole.use_shortname = off
系统字库:
cjk 中日韩英文
yum -y install google-noto-sans-thai-fonts google-noto-sans-lao-fonts google-noto-sans-khmer-fonts google-noto-sans-myanmar-fonts
php依赖库:
composer require intervention/image
样例代码:
public function svgToImg(string $svgPath, string $meetId = '000', string $outputPath = null, string $format = 'png', int $resolution = 2048)
{
try {
// 优先使用 Imagick 驱动(最稳定支持 SVG)
$manager = new ImageManager([
'driver' => 'imagick'
]);
$svgContent = file_get_contents($svgPath);
$image = $manager->make($svgContent);
// 处理分辨率参数(默认 2k = 2048px)
if ($resolution !== 2048) {
$image->resize($resolution, $resolution, function ($constraint) {
$constraint->aspectRatio();
});
}
$fileName = "summary_{$meetId}_" . Str::get_random_code(5);
// 处理默认输出路径
if (empty($outputPath)) {
$ext = (in_array(strtolower($format), ['jpeg', 'jpg'])) ? 'jpg' : 'png';
$outputPath = sys_get_temp_dir() . DIRECTORY_SEPARATOR . $fileName . '.' . $ext;
}
// 确保输出目录存在
$outputDir = dirname($outputPath);
if (!file_exists($outputDir)) {
mkdir($outputDir, 0755, true);
}
// 保存图片
if (in_array(strtolower($format), ['jpeg', 'jpg'])) {
$image->save($outputPath, 90);
} else {
$image->save($outputPath);
}
// 返回图片路径
$imagePath = realpath($outputPath);
if (!file_exists($imagePath)) {
throw new \Exception('svgToImageV2===图片文件不存在==' . $outputPath);
}
return $imagePath;
} catch (\Exception $e) {
throw new \Exception("svgToImageV2===转换失败: " . $e->getMessage());
}
}