1<?php
2/**
3 * BaconQrCode
4 *
5 * @link      http://github.com/Bacon/BaconQrCode For the canonical source repository
6 * @copyright 2013 Ben 'DASPRiD' Scholzen
7 * @license   http://opensource.org/licenses/BSD-2-Clause Simplified BSD License
8 */
9
10namespace BaconQrCode\Renderer\Image;
11
12use BaconQrCode\Exception;
13use BaconQrCode\Renderer\Color\ColorInterface;
14
15/**
16 * PNG backend.
17 */
18class Png extends AbstractRenderer
19{
20    /**
21     * Image resource used when drawing.
22     *
23     * @var resource
24     */
25    protected $image;
26
27    /**
28     * Colors used for drawing.
29     *
30     * @var array
31     */
32    protected $colors = array();
33
34    /**
35     * init(): defined by RendererInterface.
36     *
37     * @see    ImageRendererInterface::init()
38     * @return void
39     */
40    public function init()
41    {
42        $this->image = imagecreatetruecolor($this->finalWidth, $this->finalHeight);
43    }
44
45    /**
46     * addColor(): defined by RendererInterface.
47     *
48     * @see    ImageRendererInterface::addColor()
49     * @param  string         $id
50     * @param  ColorInterface $color
51     * @return void
52     * @throws Exception\RuntimeException
53     */
54    public function addColor($id, ColorInterface $color)
55    {
56        if ($this->image === null) {
57            throw new Exception\RuntimeException('Colors can only be added after init');
58        }
59
60        $color = $color->toRgb();
61
62        $this->colors[$id] = imagecolorallocate(
63            $this->image,
64            $color->getRed(),
65            $color->getGreen(),
66            $color->getBlue()
67        );
68    }
69
70    /**
71     * drawBackground(): defined by RendererInterface.
72     *
73     * @see    ImageRendererInterface::drawBackground()
74     * @param  string $colorId
75     * @return void
76     */
77    public function drawBackground($colorId)
78    {
79        imagefill($this->image, 0, 0, $this->colors[$colorId]);
80    }
81
82    /**
83     * drawBlock(): defined by RendererInterface.
84     *
85     * @see    ImageRendererInterface::drawBlock()
86     * @param  integer $x
87     * @param  integer $y
88     * @param  string  $colorId
89     * @return void
90     */
91    public function drawBlock($x, $y, $colorId)
92    {
93        imagefilledrectangle(
94            $this->image,
95            $x,
96            $y,
97            $x + $this->blockSize - 1,
98            $y + $this->blockSize - 1,
99            $this->colors[$colorId]
100        );
101    }
102
103    /**
104     * getByteStream(): defined by RendererInterface.
105     *
106     * @see    ImageRendererInterface::getByteStream()
107     * @return string
108     */
109    public function getByteStream()
110    {
111        ob_start();
112        imagepng($this->image);
113        return ob_get_clean();
114    }
115}