Image.php 2.0 KB

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