n/chit-chatu/shangshu · 2 个月前
注册 登录
n/chit-chat · 2 个月前 · 已编辑 · 81 次浏览
u/shangshu白银

用PHP 和phantomjs ,将 svg 格式的图片 转成 png 格式

<?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 条回复

排序
  1. shangshu 白银 楼主 1 个月前

    phantomjs 需要的脚本 psvg-convert.js

    #!/home/bin/env phantomjs
    
    /*
     * SVG converter to png or pdf format using PhantomJS
     *
     * Usage: svg-convert.js inputfile.svg outputfile.png [--width=800 --height=600 --zoom=2.5 --format=png|pdf]
     * 
     * author: Miroslaw Sztorc <[email protected]>
     * license: MIT
     */
    
    var sys = require('system');
    var args = sys.args;
    
    if (args.length < 3) {
        console.log("Usage: svg-convert.js inputfile.svg outputfile.png [--width=800 --height=600 --zoom=2.5 --format=png|pdf]");
        phantom.exit(1);
    }
    
    //input file
    var infile = args[1];
    
    //output file
    var outfile = args[2];
    
    //default values
    var rwidth   = 0; //auto
    var rheight  = 0; //auto
    var rzoom    = 1.0;
    var rformat  = outfile.split('.').pop().toLowerCase();
    
    var page = require('webpage').create();
    
    args.forEach(function(arg, i) {
        
        // width arg
        if (arg.trim().search('--width=') > -1)
            rwidth = arg.trim().split("=")[1];
    
        //height arg
        if (arg.trim().search('--height=') > -1)
            rheight = arg.trim().split("=")[1];
    
        //zoom arg
        if (arg.trim().search('--zoom=') > -1)
            rzoom = arg.trim().split("=")[1];
    
        //format arg
        if (arg.trim().search('--format=') > -1)
            rformat = arg.trim().split("=")[1];
    });
    
    if (rformat != 'png' && rformat != 'pdf') rformat = 'png';
    
    page.open(infile, function() {
    
        var svg = getSVGRect();
        var vBox = getSVGVBox();
    
        //new width
        var nwidth = (vBox.width > 0) ? vBox.width : svg.width;
        if (rwidth > 0) nwidth = rwidth;
    
        //new height
        var nheight = (vBox.height > 0) ? vBox.height : svg.height;
        if (rheight > 0) nheight = rheight;
    
        if (rzoom > 1) {
            nwidth = Math.round(svg.width*rzoom);
            nheight = Math.round(svg.height*rzoom);
        }
    
        window.resizeTo(nwidth, nheight);
        page.viewportSize = { width: nwidth, height: nheight };
    
        var fsvg = getSVGRect();
        //page.clipRect = { left: fsvg.left, top: fsvg.top, width: fsvg.width, height: fsvg.height };
    
        page.render(outfile, {'format': rformat });
        phantom.exit(0);
    });
    
    function getSVGRect()
    {
        return page.evaluate(function () {
            var svg = document.getElementsByTagName('svg')[0];
            return svg.getBoundingClientRect();
        });
    }
    
    function getSVGVBox()
    {
        return page.evaluate(function () {
            var svg = document.getElementsByTagName('svg')[0];
            var vba = svg.getAttribute('viewBox');
    
            var vBox = { 'left': 0, 'top': 0, 'width': 0, 'height': 0 };
    
            if (vba != null && vba != '' && vba.split(' ').length == 4)
            {
                var vb = vba.split(' ');
    
                vBox.left = parseFloat(vb[0]);
                vBox.top = parseFloat(vb[1]);
                vBox.width = parseFloat(vb[2]);
                vBox.height = parseFloat(vb[3]);
            }
    
            return vBox;
        })
    
    }
    
    0
  2. jamisky 黄金 1 个月前

    牛逼!

    0