<?php
# svg 转成 png
# 需要 phantomjs,下载地址 https://phantomjs.org/download.html
$svg_file = '/docs/temp/article_images/3878415931.svg'; // $svg_content = file_get_contents($svg_file);
$bin = 'phantomjs psvg-convert.js '; # 没有设置为环境变量时,需要指定路径
$zoom=2.5;
$format = 'png';
$png_file = str_replace('.svg', '.png', $svg_file);
$svg2 = simplexml_load_file($svg_file);
// $array = json_decode(json_encode($svg2), true); # Object 转为 Array,用 var_dump / print_r 查看
$width = $svg2 -> attributes() -> width; // echo $width;
$height = $svg2 -> attributes() -> height; // echo $height;
settype($width, "float");
settype($height, "float");
$cmd = $bin . $svg_file . ' ' . $png_file . ' --width=' . $width . ' --height=' . $height . ' --zoom=2.5 --format=png';
exec($cmd, $output, $return_value);
if (!$return_value) $png_content = file_get_contents($png_file);
else die('指令未执行');
$png_content = mergeWithCanvas($png_content, $width, $height);
file_put_contents($png_file, $png_content);
# 裁切复制图片
function mergeWithCanvas($png_content, $width, $height){
if (class_exists('Imagick')){
$image = new \Imagick();
$image -> readImageBlob($png_content);
// $image->resizeImage($width, $height, \Imagick::FILTER_LANCZOS, 1, true);
$ow = $image -> getImageWidth();
$oh = $image -> getImageHeight();echo $oh;
$offset_x = round(($width - $ow) / 2);
$offset_y = round(($height - $oh) / 2);
$image -> extentImage($width, $height, -$offset_x, -$offset_y);
$image -> setImageBackgroundColor('white');
$png_content = $image -> getImageBlob();
}
if (function_exists('imageantialias')){
$image = imagecreatefromstring($png_content);
imageantialias($image, true);
$ow = imagesx($image);
$oh = imagesy($image); # png 图片的尺寸
# 创建一张黑色的图像
$canvas = imagecreatetruecolor($width, $height);
# 用 white 填充
$white = imagecolorallocatealpha($canvas, 255, 255, 255, 127);
imagefill($canvas, 0, 0, $white);
// imagecopy($canvas, $image, round(($width - $ow) / 2), round(($height - $oh) / 2), 0, 0, $ow, $oh);
imagecopy($canvas, $image, 0, 0, 0, 0, $width, $height);
ob_start();
imagepng($canvas);
$png_content = ob_get_clean();
}
return $png_content;
}
0
2
2 การตอบกลับ
การเรียงลำดับ