Chris@0
|
1 <?php
|
Chris@0
|
2
|
Chris@0
|
3 namespace Drupal\Component\Utility;
|
Chris@0
|
4
|
Chris@0
|
5 /**
|
Chris@0
|
6 * Provides helpers to operate on images.
|
Chris@0
|
7 *
|
Chris@0
|
8 * @ingroup utility
|
Chris@0
|
9 */
|
Chris@0
|
10 class Image {
|
Chris@0
|
11
|
Chris@0
|
12 /**
|
Chris@0
|
13 * Scales image dimensions while maintaining aspect ratio.
|
Chris@0
|
14 *
|
Chris@0
|
15 * The resulting dimensions can be smaller for one or both target dimensions.
|
Chris@0
|
16 *
|
Chris@0
|
17 * @param array $dimensions
|
Chris@0
|
18 * Dimensions to be modified - an array with components width and height, in
|
Chris@0
|
19 * pixels.
|
Chris@0
|
20 * @param int $width
|
Chris@0
|
21 * (optional) The target width, in pixels. If this value is NULL then the
|
Chris@0
|
22 * scaling will be based only on the height value.
|
Chris@0
|
23 * @param int $height
|
Chris@0
|
24 * (optional) The target height, in pixels. If this value is NULL then the
|
Chris@0
|
25 * scaling will be based only on the width value.
|
Chris@0
|
26 * @param bool $upscale
|
Chris@0
|
27 * (optional) Boolean indicating that images smaller than the target
|
Chris@0
|
28 * dimensions will be scaled up. This generally results in a low quality
|
Chris@0
|
29 * image.
|
Chris@0
|
30 *
|
Chris@0
|
31 * @return bool
|
Chris@0
|
32 * TRUE if $dimensions was modified, FALSE otherwise.
|
Chris@0
|
33 *
|
Chris@0
|
34 * @see image_scale()
|
Chris@0
|
35 */
|
Chris@0
|
36 public static function scaleDimensions(array &$dimensions, $width = NULL, $height = NULL, $upscale = FALSE) {
|
Chris@0
|
37 $aspect = $dimensions['height'] / $dimensions['width'];
|
Chris@0
|
38
|
Chris@0
|
39 // Calculate one of the dimensions from the other target dimension,
|
Chris@0
|
40 // ensuring the same aspect ratio as the source dimensions. If one of the
|
Chris@0
|
41 // target dimensions is missing, that is the one that is calculated. If both
|
Chris@0
|
42 // are specified then the dimension calculated is the one that would not be
|
Chris@0
|
43 // calculated to be bigger than its target.
|
Chris@0
|
44 if (($width && !$height) || ($width && $height && $aspect < $height / $width)) {
|
Chris@0
|
45 $height = (int) round($width * $aspect);
|
Chris@0
|
46 }
|
Chris@0
|
47 else {
|
Chris@0
|
48 $width = (int) round($height / $aspect);
|
Chris@0
|
49 }
|
Chris@0
|
50
|
Chris@0
|
51 // Don't upscale if the option isn't enabled.
|
Chris@0
|
52 if (!$upscale && ($width >= $dimensions['width'] || $height >= $dimensions['height'])) {
|
Chris@0
|
53 return FALSE;
|
Chris@0
|
54 }
|
Chris@0
|
55
|
Chris@0
|
56 $dimensions['width'] = $width;
|
Chris@0
|
57 $dimensions['height'] = $height;
|
Chris@0
|
58 return TRUE;
|
Chris@0
|
59 }
|
Chris@0
|
60
|
Chris@0
|
61 }
|