Gitlab CSE Unil

utils_stamp.php 12.1 KB
Newer Older
M. Chardon's avatar
M. Chardon committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
<?php

// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

/**
 * This file contains the editor class for the assignfeedback_editpdfplus plugin
 *
 * @package   assignfeedback_editpdfplus
 * @copyright  2018 Université de Lausanne
 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */

namespace assignfeedback_editpdfplus;

use \assignfeedback_editpdfplus\utils_color;

/**
 * This class performs crud operations on stamp using font FontAwesome.
 *
 * No capability checks are done - they should be done by the calling class.
 * 
 * Inspired by https://github.com/exiang/php-font-awesome-to-png
 *
 * @package   assignfeedback_editpdfplus
 * @copyright 2018 Marion Chardon
 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
class utils_stamp {

    /** Path of fontawesome font scss */
    const FA_SCSS_PATH = '/lib/fonts/font-awesome-4.7.0/scss/_variables.scss';

    /** Path of fontawesome font */
    const FA_PATH = '/lib/fonts/fontawesome-webfont.ttf';

    /** File area for the stamps */
    const STAMPS_FILEAREA = '/temp/assignfeedback_editpdfplus/stamps/';

    /**
     * Convert a FontAwesome icon into a PNG file
     * Main method 
     * 
     * @param String $iconName The name of the FontAwesome icon, for example if you need fa-user, give "user"
     * @param String $color The color in which you want to display the PNG, default black
     * @param type $fontSize The size of the font in which you want to display the PNG, default 48
     * @return String The path of the PNG file generate, or null if the convertion failed
     */
    public static function getPngFromFont($iconName, $color = "black", $fontSize = 48) {
        global $CFG;

        //get hexa code from the key iconName
        $charFAHexaCode = self::getUniCode($iconName);
        if (!$charFAHexaCode) {
            return null;
        }

        //create final file
        $outputDirectory = $CFG->dataroot . self::STAMPS_FILEAREA;
        $fileName = sprintf("%s%s.png", $outputDirectory, $iconName);

74
75
76
77
78
79
        $dirPath = dirname($fileName);
        if (!is_dir($dirPath) || !file_exists($dirPath)) {
            //try to create the directory
            self::mkdirRecursive($dirPath, 0777);
        }

M. Chardon's avatar
M. Chardon committed
80
81
82
83
84
85
86
        //get RGB color
        $colorRGB = utils_color::hex2RGB($color);

        //put image into file and return
        return self::putIconIntoFile($charFAHexaCode, $fileName, $colorRGB, $fontSize);
    }

87
88
89
90
91
92
93
94
95
96
97
98
    /**
     * Create a final directory with its path
     * 
     * @param String $pathname Path to final directory to create
     * @param String $mode Linux right
     * @return Boolean If directory is created
     */
    public static function mkdirRecursive($pathname, $mode) {
        is_dir(dirname($pathname)) || mkdir_recursive(dirname($pathname), $mode);
        return is_dir($pathname) || @mkdir($pathname, $mode);
    }

M. Chardon's avatar
M. Chardon committed
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
    /**
     * Write a chart into a PNG file
     * 
     * @param String $charFACode Chart to represent (unicode)
     * @param String $fileName The PNG final file
     * @param array $colorRGB The color in which you want to display the PNG, default black
     * @param int $fontSize The size of the font in which you want to display the PNG
     * @return String The path of the PNG file generate, or null if the convertion failed
     */
    public static function putIconIntoFile($charFACode, $fileName, $colorRGB, $fontSize) {
        global $CFG;

        //Calculate sizes
        $width = $height = $fontSize * 3;
        $padding = (int) ceil(($fontSize / 25));

        // Create the image
        $imageTmp = imagecreatetruecolor($width, $height);
        imagealphablending($imageTmp, false);

        // Create font colors
120
        $fontColor = imagecolorallocate($imageTmp, $colorRGB['red'], $colorRGB['green'], $colorRGB['blue']);
M. Chardon's avatar
M. Chardon committed
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
        $background = imagecolorallocatealpha($imageTmp, 255, 0, 255, 127);

        // Draw rectangle
        imagefilledrectangle($imageTmp, 0, 0, $width, $height, $background);
        imagealphablending($imageTmp, true);

        // Add the text using the Font
        $fontPath = $CFG->dirroot . self::FA_PATH;
        list($fontX, $fontY) = self::imageTTFCenter($imageTmp, $charFACode, $fontPath, $fontSize);
        imagettftext($imageTmp, $fontSize, 0, $fontX, $fontY, $fontColor, $fontPath, $charFACode);
        imagealphablending($imageTmp, false);
        imagesavealpha($imageTmp, true);

        //Center the image
        self::imageTrim($imageTmp, $background, $padding);

        //Resize the image
        self::imageCanvas($imageTmp, $fontSize, $background, $padding);

        //convert image to PNG
        imagepng($imageTmp, $fileName);

        //purge memory
        imagedestroy($imageTmp);

        return $fileName;
    }

    /**
     * Calculate and set the center position of an image given by the size of a text in its font representation
     * 
     * @param resource $image Reference image
     * @param String $text Text to insert into the image
     * @param String $font Font path
     * @param int $size Font size into display the text
     * @param int $angle Angle into display the text, default 45°
     * @return array the center position
     */
    public static function imageTTFCenter($image, $text, $font, $size, $angle = 45) {
        $xi = imagesx($image);
        $yi = imagesy($image);

        // create a bounding box for the first text
        $box = imagettfbbox($size, $angle, $font, $text);

        // get dimension of the box 
        $xr = abs(max($box[2], $box[4]));
        $yr = abs(max($box[5], $box[7]));

        // compute centering
        $x = intval(($xi - $xr) / 2);
        $y = intval(($yi + $yr) / 2);

        return array($x, $y);
    }

    /**
     * Position and assemblate image and background
     * 
     * @param resource $image Final image to arrange
     * @param int $background Color and alpha background
     * @param int $padding Space between chart and border
     */
    public static function imageTrim(&$image, $background, $padding = null) {

        // Calculate padding for each side.
        if (isset($padding)) {
            $pp = explode(' ', $padding);
            if (isset($pp[3])) {
                $p = array((int) $pp[0], (int) $pp[1], (int) $pp[2], (int) $pp[3]);
            } else if (isset($pp[2])) {
                $p = array((int) $pp[0], (int) $pp[1], (int) $pp[2], (int) $pp[1]);
            } else if (isset($pp[1])) {
                $p = array((int) $pp[0], (int) $pp[1], (int) $pp[0], (int) $pp[1]);
            } else {
                $p = array_fill(0, 4, (int) $pp[0]);
            }
        } else {
            $p = array_fill(0, 4, 0);
        }

        // Get the image width and height.
        $imageWidth = imagesx($image);
        $imageHeight = imagesy($image);

        // Set the X variables.
        $xmin = $imageWidth;
        $xmax = 0;

        // Start scanning for the edges.
        for ($iy = 0; $iy < $imageHeight; $iy++) {
            $first = true;
            for ($ix = 0; $ix < $imageWidth; $ix++) {
                if (imagecolorat($image, $ix, $iy) == $background) {
                    continue;
                }
                $xmin = ($xmin > $ix) ? $ix : $xmin;
                $xmax = ($xmax < $ix) ? $ix : $xmax;
                $ymin = (!isset($ymin)) ? $iy : $ymin;
                $ymax = $iy;
                $ix = ($first) ? $xmax : $ix;
                $first = false;
            }
        }

        // The new width and height of the image. (not including padding)
        $imageNewWidth = 1 + $xmax - $xmin; // Image width in pixels
        $imageNewHeight = 1 + $ymax - $ymin; // Image height in pixels
        // Make another image to place the trimmed version in.
        $image2 = imagecreatetruecolor($imageNewWidth + $p[1] + $p[3], $imageNewHeight + $p[0] + $p[2]);

        // Make the background of the new image the same as the background of the old one.
        $bg2 = imagecolorallocatealpha($image2, ($background >> 16) & 0xFF, ($background >> 8) & 0xFF, $background & 0xFF, 127);
        imagefill($image2, 0, 0, $bg2);
        imagealphablending($image2, true);

        // Copy it over to the new image.
        imagecopy($image2, $image, $p[3], $p[0], $xmin, $ymin, $imageNewWidth, $imageNewHeight);

        // To finish up, we replace the old image which is referenced.
        imagealphablending($image2, false);
        imagesavealpha($image2, true);
        $image = $image2;
    }

    /**
     * Crop an image according to the size parameter
     * 
     * @param resource $image the image to resize
     * @param int $size New size
     * @param int $background color and alpha background
     * @param int $padding space between image content and border
     */
    public static function imageCanvas(&$image, $size, $background, $padding) {
        $sourceWidth = imagesx($image);
        $ssourceHeight = imagesy($image);

        //create a second image to put the result with operation on the $image
        $image2 = imagecreatetruecolor($size, $size);
        $background2 = imagecolorallocatealpha($image2, ($background >> 16) & 0xFF, ($background >> 8) & 0xFF, $background & 0xFF, 127);
        imagefill($image2, 0, 0, $background2);
        imagealphablending($image2, true);

        // init
        $sourceX = $sourceY = 0;
        $destinationWidth = $destinationtHeight = $size;

        // if source size is smaller than output size
        if ($sourceWidth < $size && $ssourceHeight < $size) {
            $destinationWidth = $sourceWidth;
            $destinationtHeight = $ssourceHeight;
        }
        // if source is bigger than output
        else {
            // use padding
            // if horizontal long
            if ($sourceWidth > $ssourceHeight) {
                $destinationWidth = $size - $padding;
                $destinationtHeight = (int) (($destinationWidth / $sourceWidth) * $ssourceHeight);
            }
            // if vertically long or equal(square)
            else {
                $destinationtHeight = $size - $padding;
                $destinationWidth = (int) (($destinationtHeight / $ssourceHeight) * $sourceWidth);
            }
        }

        //Calculate new coordonates
        $destinationX = (int) (($size - $destinationWidth) / 2);
        $destinationY = (int) (($size - $destinationtHeight) / 2);

        //Copy and resize the fist image into image2
        imagecopyresampled($image2, $image, $destinationX, $destinationY, $sourceX, $sourceY, $destinationWidth, $destinationtHeight, $sourceWidth, $ssourceHeight);

        //finalize image2
        imagealphablending($image2, false);
        imagesavealpha($image2, true);

        //replace image with image2
        $image = $image2;
    }

    /**
     * Get unicode of a icon reprented in FontAwesome, using the scss file
     * 
     * @param String $iconName
     * @return String unicode or null if no correspondance
     */
    public static function getUniCode($iconName) {
        global $CFG;

        //open scss file
        $readBuffer = file_get_contents($CFG->dirroot . self::FA_SCSS_PATH);
        $lines = explode("\n", $readBuffer);

        //get all lines to search the hexa code from key
        foreach ($lines as $l) {
            if (!strstr($l, '$fa-var-')) {
                continue;
            }
            $lArray = explode(":", $l);
            $key = str_replace('$fa-var-', '', trim($lArray[0]));
            if ($key == $iconName) {
                $value = str_replace(array('"'), '', trim($lArray[1]));
                $value2Write = str_replace('\\', '&#x', $value);
                return $value2Write;
            }
        }

        return null;
    }

}