php中图片转svg格式及svg转图片的实现方式

php中图片转svg格式及svg转图片的实现方式

php中图片转svg格式及svg转图片的实现方式

现在svg的普及随着html5的普及而推广开来,svg矢量相比较位图更加有优势,那么如何将传统的位图通过php转换成svg呢?还有就是svg图片又如何转换成传统的图片呢,今天我来给大家一一解答

一、图片转svg

php中没有直接的函数可以将图片转成svg,但是我们可以通过其他的办法,GD库是一种选择,原理就是通过gd库读取图片的每个像素点,然后生成一个rect组合起来,具体核心代码如下

<?php
$size = getimagesize($filename);
$width = $size[0];
$height = $size[1];
// open image into a true color image
$orimage = imagecreatefrompng($filename);
$im = imagecreatetruecolor($width, $height);
imagecopyresampled($im, $orimage, 0, 0, 0, 0, $width, $height, $width, $height);
$svg = "";
// header
output_head();
// body
$colors = array();
for ($y = 0; $y < $height; $y++) {
    for ($x = 0; $x < $width; $x++) {
        // get pixel at (x,y)
        $rgb = imagecolorat($im, $x, $y);
        $r = ($rgb >> 16) & 0xFF;
        $g = ($rgb >> 8) & 0xFF;
        $b = $rgb & 0xFF;
        // skip black pixels
        if ($rgb == 0) continue;
        $color = sprintf("#%02x%02x%02x", $r, $g, $b);
        // calculate color for border
        $dark_factor = 0.9;
        $border_color = sprintf(
            "#%02x%02x%02x",
            (int) ($r * $dark_factor),
            (int) ($g * $dark_factor),
            (int) ($b * $dark_factor)
        );
        // calculamos el estilo del pixel
        $style = $pixel_style;
        $style['fill'] = $color;
        $style['stroke'] = $border_color;
        // guardamos el estilo para el color key
        if (!isset($colors[$rgb])) {
            $colors[$rgb] = $style;
        }
        $svg .= '<svg:rect height="10" width="10" x="' . $x * $pixel_size . '" y="' . $y * $pixel_size . '" style="' . to_svg_style($style) . '" />';
        $svg .= "\n";
?>

注意:这个转换方式只适合转体积小的png图片,不适合转大型图片

二、svg转图片

svg转图片的话直接使用一个开源的php库SVG.PHP,他已经写好的相关方法,可以直接调用

<?php
require("../autoloader.php");
use SVG\SVG;
use SVG\Nodes\Shapes\SVGCircle;
//此处实现了svg文件转换成image图片格式
$svg  = '<svg width="100" height="100">';
$svg .= '<rect width="50" height="50" fill="#00F" />';
$svg .= '</svg>';

$image = SVG::fromString($svg);
$doc = $image->getDocument();

$rect = $doc->getChild(0);
$rect->setX(25)->setY(25);

// rasterize to a 200x200 image, i.e. the original SVG size scaled by 2.
// the background will be transparent by default.
$rasterImage = $image->toRasterImage(200, 200);
header('Content-Type: image/png');
imagepng($rasterImage);
?>

以上两种方式可以直接打开webide地址进行编辑运行,项目webdie地址:http://studio.bfw.wiki/Studio/Open.html?projectid=15765515565156090082




{{collectdata}}

网友评论0