底辺SE奮闘記

年収300万SEブログ

【PHP】SVG(with text) convert to PNG and save by "meyfa/php-svg"

Postscript

I wrote an article about "meyfa/php-svg" in detail.

uma-no-kawa.hateblo.jp

Environment

github.com

How to introduce "meyfa/php-svg"

Introduce with the composer.

composer require meyfa/php-svg

If you will use text writing, you must set next setting, other than "gd".

--with-freetype-dir=/usr

If you use "phpenv", you add previous setting to bellow file.

(MAC)

$HOME/.phpenv/plugins/php-build/share/php-build/default_configure_options

and,

phpenv uninstall [php version]
phpenv install [php version]

How to use

<?php
use SVG\SVG;
use SVG\Nodes\Texts\SVGText;
use SVG\Nodes\Structures\SVGFont;

//Prepare svg file
$svg = '<svg xmlns="http://www.w3.org/2000/svg" width="500" height="500" viewBox="0 0 500 500">
    <circle cx="150" cy="200" r="100" fill="#06f"></circle>
    </svg>';
$image = SVG::fromString($svg);

//If you use text
$font = new SVGFont('IPAex明朝', "font/ipaexm.ttf");
$image->getDocument()->addChild($font);
$image->getDocument()->addChild(
    (new SVGText('Hello World', 50, 50))
        ->setFont($font)
        ->setSize(30)
        ->setStyle('fill', '#f00')
    );

//Rasterize image
$rasterImage = $image->toRasterImage(500, 500);

// if you show to browser
echo $image->toXMLString();

// if you save to image file
imagepng($rasterImage, "my-image.png");

About using font

I used font of bellow site. thank u.

ipafont.ipa.go.jp