generated from FriendsOfREDAXO/rex_repo_template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathForThumbHashHelper.php
96 lines (75 loc) · 2.61 KB
/
ForThumbHashHelper.php
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
<?php
declare(strict_types=1);
namespace FriendsOfRedaxo\ThumbHash;
use GdImage;
final class ForThumbHashHelper
{
/** @var int */
private const MAX_IMAGE_SIZE = 100;
/**
* Get width+height and pixels from image (string) aspect ratio. Resized to maximum size 100px.
* @api
*/
public static function getSizeAndPixels(string $content): mixed
{
$source = imagecreatefromstring($content);
$pixels = [];
if (false !== $source) {
$width = imagesx($source);
$height = imagesy($source);
$imgRatio = $width / $height;
// dump($width, $height, $imgRatio);
if ($imgRatio > 1) {
$newwidth = self::MAX_IMAGE_SIZE;
$newheight = (int) (self::MAX_IMAGE_SIZE / $imgRatio);
} else {
$newwidth = (int) (self::MAX_IMAGE_SIZE * $imgRatio);
$newheight = self::MAX_IMAGE_SIZE;
}
// dump($newwidth, $newheight);
$thumb = imagecreatetruecolor($newwidth, $newheight);
if (false !== $thumb) {
imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
$width = $newwidth;
$height = $newheight;
$pixels = self::getPixels($thumb, $width, $height);
}
return [$width, $height, $pixels];
}
return false;
}
/**
* Get width+height and pixels from image (filename) aspect ratio. Resized to maximum size 100px.
* @api
*/
public static function getSizeAndPixelsFromFile(string $filename): mixed
{
$content = file_get_contents($filename);
if (false !== $content) {
return self::getSizeAndPixels($content);
}
return false;
}
/**
* Get pixels from image.
* @api
*/
public static function getPixels(GdImage $thumb, int $width, int $height): mixed
{
$pixels = [];
for ($y = 0; $y < $height; ++$y) {
for ($x = 0; $x < $width; ++$x) {
$color_index = imagecolorat($thumb, $x, $y);
if (false !== $color_index) {
$color = imagecolorsforindex($thumb, $color_index);
$alpha = 255 - ceil($color['alpha'] * (255 / 127)); // GD only supports 7-bit alpha channel
$pixels[] = $color['red'];
$pixels[] = $color['green'];
$pixels[] = $color['blue'];
$pixels[] = $alpha;
}
}
}
return $pixels;
}
}