-
Notifications
You must be signed in to change notification settings - Fork 133
Expand file tree
/
Copy pathFontUtility.php
More file actions
79 lines (66 loc) · 2.4 KB
/
FontUtility.php
File metadata and controls
79 lines (66 loc) · 2.4 KB
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
74
75
76
77
78
79
<?php
namespace Photobooth\Utility;
class FontUtility
{
public const supportedFileExtensionsProcessing = [
'ttf',
];
public const supportedFileExtensionsSelect = [
'ttf',
];
public const supportedMimeTypesSelect = [
'font/ttf',
'application/octet-stream',
];
public static function getFontPreviewImage(
string $fontPath,
int $width = 300,
int $height = 200,
int $fontSize = 34,
array $textLines = [
'Photobooth!',
'We love',
'OpenSource.'
],
array $attributes = [],
): string {
$absoluteFontPath = PathUtility::resolveFilePath($fontPath);
$lineHeight = (int) round($fontSize * 1.5);
$image = imagecreatetruecolor($width, $height);
$backgroundColor = (int) imagecolorallocate($image, 255, 255, 255);
imagefilledrectangle($image, 0, 0, $width - 1, $height - 1, $backgroundColor);
if (is_readable($absoluteFontPath)) {
$textColor = (int) imagecolorallocate($image, 0, 0, 0);
$x = 10;
$y = $lineHeight;
foreach ($textLines as $line) {
imagefttext($image, $fontSize, 0, $x, $y, $textColor, $absoluteFontPath, $line);
$y += $lineHeight;
}
}
ob_start();
imagepng($image);
$imageData = (string) ob_get_contents();
ob_end_clean();
imagedestroy($image);
$attributes['src'] = 'data:image/png;base64,' . base64_encode($imageData);
return '<img ' . ComponentUtility::renderAttributes($attributes) . '>';
}
public static function getFontsFromPath(string $path, bool $processing = true): array
{
if (!PathUtility::isAbsolutePath($path)) {
$path = PathUtility::getAbsolutePath($path);
}
if (!PathUtility::isAbsolutePath($path)) {
throw new \Exception('Path ' . $path . ' does not exist.');
}
$files = [];
foreach (new \DirectoryIterator($path) as $file) {
if (!$file->isFile() || !in_array(strtolower($file->getExtension()), $processing ? self::supportedFileExtensionsProcessing : self::supportedFileExtensionsSelect)) {
continue;
}
$files[$file->getBasename('.' . $file->getExtension())] = $path . '/' . $file->getFilename();
}
return $files;
}
}