Completed
Push — master ( 29743b...f250f7 )
by Mikael
03:04
created

CAsciiArt.php (1 issue)

Severity

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
/**
3
 * Create an ASCII version of an image.
4
 *
5
 */
6
class CAsciiArt
7
{
8
    /**
9
     * Character set to use.
10
     */
11
    private $characterSet = array(
12
        'one' => "#0XT|:,.' ",
13
        'two' => "@%#*+=-:. ",
14
        'three' => "$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,\"^`'. "
15
    );
16
17
18
19
    /**
20
     * Current character set.
21
     */
22
    private $characters = null;
23
24
25
26
    /**
27
     * Length of current character set.
28
     */
29
    private $charCount = null;
30
31
32
33
    /**
34
     * Scale of the area to swap to a character.
35
     */
36
    private $scale = null;
37
38
39
40
    /**
41
     * Strategy to calculate luminance.
42
     */
43
    private $luminanceStrategy = null;
44
45
46
47
    /**
48
     * Constructor which sets default options.
49
     */
50
    public function __construct()
51
    {
52
        $this->setOptions();
53
    }
54
55
56
57
    /**
58
     * Add a custom character set.
59
     *
60
     * @param string $key   for the character set.
61
     * @param string $value for the character set.
62
     *
63
     * @return $this
64
     */
65
    public function addCharacterSet($key, $value)
66
    {
67
        $this->characterSet[$key] = $value;
68
        return $this;
69
    }
70
71
72
73
    /**
74
     * Set options for processing, defaults are available.
75
     *
76
     * @param array $options to use as default settings.
77
     *
78
     * @return $this
79
     */
80
    public function setOptions($options = array())
81
    {
82
        $default = array(
83
            "characterSet" => 'two',
84
            "scale" => 14,
85
            "luminanceStrategy" => 3,
86
            "customCharacterSet" => null,
87
        );
88
        $default = array_merge($default, $options);
89
        
90
        if (!is_null($default['customCharacterSet'])) {
91
            $this->addCharacterSet('custom', $default['customCharacterSet']);
92
            $default['characterSet'] = 'custom';
93
        }
94
        
95
        $this->scale = $default['scale'];
96
        $this->characters = $this->characterSet[$default['characterSet']];
97
        $this->charCount = strlen($this->characters);
98
        $this->luminanceStrategy = $default['luminanceStrategy'];
99
        
100
        return $this;
101
    }
102
103
104
105
    /**
106
     * Create an Ascii image from an image file.
107
     *
108
     * @param string $filename of the image to use.
109
     *
110
     * @return string $ascii with the ASCII image.
111
     */
112
    public function createFromFile($filename)
113
    {
114
        $img = imagecreatefromstring(file_get_contents($filename));
0 ignored issues
show
Security File Exposure introduced by
$filename can contain request data and is used in file inclusion context(s) leading to a potential security vulnerability.

General Strategies to prevent injection

In general, it is advisable to prevent any user-data to reach this point. This can be done by white-listing certain values:

if ( ! in_array($value, array('this-is-allowed', 'and-this-too'), true)) {
    throw new \InvalidArgumentException('This input is not allowed.');
}

For numeric data, we recommend to explicitly cast the data:

$sanitized = (integer) $tainted;
Loading history...
115
        list($width, $height) = getimagesize($filename);
116
117
        $ascii = null;
118
        $incY = $this->scale;
119
        $incX = $this->scale / 2;
120
        
121
        for ($y = 0; $y < $height - 1; $y += $incY) {
122
            for ($x = 0; $x < $width - 1; $x += $incX) {
123
                $toX = min($x + $this->scale / 2, $width - 1);
124
                $toY = min($y + $this->scale, $height - 1);
125
                $luminance = $this->luminanceAreaAverage($img, $x, $y, $toX, $toY);
126
                $ascii .= $this->luminance2character($luminance);
127
            }
128
            $ascii .= PHP_EOL;
129
        }
130
131
        return $ascii;
132
    }
133
134
135
136
    /**
137
     * Get the luminance from a region of an image using average color value.
138
     *
139
     * @param string  $img the image.
140
     * @param integer $x1  the area to get pixels from.
141
     * @param integer $y1  the area to get pixels from.
142
     * @param integer $x2  the area to get pixels from.
143
     * @param integer $y2  the area to get pixels from.
144
     *
145
     * @return integer $luminance with a value between 0 and 100.
146
     */
147
    public function luminanceAreaAverage($img, $x1, $y1, $x2, $y2)
148
    {
149
        $numPixels = ($x2 - $x1 + 1) * ($y2 - $y1 + 1);
150
        $luminance = 0;
151
        
152
        for ($x = $x1; $x <= $x2; $x++) {
153
            for ($y = $y1; $y <= $y2; $y++) {
154
                $rgb   = imagecolorat($img, $x, $y);
155
                $red   = (($rgb >> 16) & 0xFF);
156
                $green = (($rgb >> 8) & 0xFF);
157
                $blue  = ($rgb & 0xFF);
158
                $luminance += $this->getLuminance($red, $green, $blue);
159
            }
160
        }
161
        
162
        return $luminance / $numPixels;
163
    }
164
165
166
167
    /**
168
     * Calculate luminance value with different strategies.
169
     *
170
     * @param integer $red   The color red.
171
     * @param integer $green The color green.
172
     * @param integer $blue  The color blue.
173
     *
174
     * @return float $luminance with a value between 0 and 1.
175
     */
176
    public function getLuminance($red, $green, $blue)
177
    {
178
        switch($this->luminanceStrategy) {
179
            case 1:
180
                $luminance = ($red * 0.2126 + $green * 0.7152 + $blue * 0.0722) / 255;
181
                break;
182
            case 2:
183
                $luminance = ($red * 0.299 + $green * 0.587 + $blue * 0.114) / 255;
184
                break;
185
            case 3:
186
                $luminance = sqrt(0.299 * pow($red, 2) + 0.587 * pow($green, 2) + 0.114 * pow($blue, 2)) / 255;
187
                break;
188
            case 0:
189
            default:
190
                $luminance = ($red + $green + $blue) / (255 * 3);
191
        }
192
193
        return $luminance;
194
    }
195
196
197
198
    /**
199
     * Translate the luminance value to a character.
200
     *
201
     * @param string $position a value between 0-100 representing the
202
     *                         luminance.
203
     *
204
     * @return string with the ascii character.
205
     */
206
    public function luminance2character($luminance)
207
    {
208
        $position = (int) round($luminance * ($this->charCount - 1));
209
        $char = $this->characters[$position];
210
        return $char;
211
    }
212
}
213