-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathImage.php
84 lines (76 loc) · 2.78 KB
/
Image.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
<?php
namespace Drupal\Component\Utility;
/**
* Provides helpers to operate on images.
*
* @ingroup utility
*/
class Image {
/**
* Scales image dimensions while maintaining aspect ratio.
*
* The resulting dimensions can be smaller for one or both target dimensions.
*
* @param array $dimensions
* Dimensions to be modified - an array with components width and height, in
* pixels.
* @param int $width
* (optional) The target width, in pixels. If this value is NULL then the
* scaling will be based only on the height value.
* @param int $height
* (optional) The target height, in pixels. If this value is NULL then the
* scaling will be based only on the width value.
* @param bool $upscale
* (optional) Boolean indicating that images smaller than the target
* dimensions will be scaled up. This generally results in a low quality
* image.
*
* @return bool
* TRUE if $dimensions was modified, FALSE otherwise.
*/
public static function scaleDimensions(array &$dimensions, $width = NULL, $height = NULL, $upscale = FALSE) {
$aspect = $dimensions['height'] / $dimensions['width'];
// Calculate one of the dimensions from the other target dimension,
// ensuring the same aspect ratio as the source dimensions. If one of the
// target dimensions is missing, that is the one that is calculated. If both
// are specified then the dimension calculated is the one that would not be
// calculated to be bigger than its target.
if (($width && !$height) || ($width && $height && $aspect < $height / $width)) {
$height = (int) round($width * $aspect);
}
else {
$width = (int) round($height / $aspect);
}
// Don't upscale if the option isn't enabled.
if (!$upscale && ($width >= $dimensions['width'] || $height >= $dimensions['height'])) {
return FALSE;
}
$dimensions['width'] = $width;
$dimensions['height'] = $height;
return TRUE;
}
/**
* Returns the offset in pixels from the anchor.
*
* @param string $anchor
* The anchor ('top', 'left', 'bottom', 'right', 'center').
* @param int $current_size
* The current size, in pixels.
* @param int $new_size
* The new size, in pixels.
*
* @return int
* The offset from the anchor, in pixels.
*
* @throws \InvalidArgumentException
* When the $anchor argument is not valid.
*/
public static function getKeywordOffset(string $anchor, int $current_size, int $new_size): int {
return match ($anchor) {
'bottom', 'right' => $current_size - $new_size,
'center' => (int) round($current_size / 2 - $new_size / 2),
'top', 'left' => 0,
default => throw new \InvalidArgumentException("Invalid anchor '{$anchor}' provided to getKeywordOffset()"),
};
}
}