SvgExtractor::get()   A
last analyzed

Complexity

Conditions 5
Paths 3

Size

Total Lines 28

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 28
rs 9.1608
c 0
b 0
f 0
cc 5
nc 3
nop 2
1
<?php
2
3
namespace Imagecow\Utils;
4
5
use Exception;
6
use Imagick;
7
use ImagickPixel;
8
use Imagecow;
9
10
/**
11
 * Simple class to convert a svg file to png
12
 * Requires Imagick.
13
 */
14
class SvgExtractor
15
{
16
    protected $image;
17
18
    /**
19
     * Contructor.
20
     *
21
     * @param string $filename The path of the svg file
22
     */
23
    public function __construct($filename)
24
    {
25
        if (!extension_loaded('imagick')) {
26
            throw new Exception('SvgExtractor needs imagick extension');
27
        }
28
29
        $image = new Imagick();
30
        $image->setBackgroundColor(new ImagickPixel('transparent'));
31
32
        if (!is_file($filename)) {
33
            throw new Exception("'$filename' is not a readable file");
34
        }
35
36
        $image->readImage($filename);
37
38
        $this->image = $image;
39
    }
40
41
    /**
42
     * Get the svg as an image.
43
     *
44
     * @return \Imagecow\Image
45
     */
46
    public function get($width = 0, $height = 0)
47
    {
48
        $imageWidth = $this->image->getImageWidth();
49
        $imageHeight = $this->image->getImageHeight();
50
51
        if ($width !== 0 && ($height === 0 || ($imageWidth / $width) > ($imageHeight / $height))) {
52
            $height = ceil(($width / $imageWidth) * $imageHeight);
53
        } elseif ($height !== 0) {
54
            $width = ceil(($height / $imageHeight) * $imageWidth);
55
        } else {
56
            $width = $imageWidth;
57
            $height = $imageHeight;
58
        }
59
60
        $image = new Imagick();
61
        $image->setBackgroundColor(new ImagickPixel('transparent'));
62
        $image->setResolution($width, $height);
63
64
        $blob = $this->image->getImageBlob();
65
66
        $blob = preg_replace('/<svg([^>]*) width="([^"]*)"/si', '<svg$1 width="'.$width.'px"', $blob);
67
        $blob = preg_replace('/<svg([^>]*) height="([^"]*)"/si', '<svg$1 height="'.$height.'px"', $blob);
68
69
        $image->readImageBlob($blob);
70
        $image->setImageFormat('png');
71
72
        return new Imagecow\Image(new Imagecow\Libs\Imagick($image));
73
    }
74
}
75