Image.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. * @see image_scale()
  32. */
  33. public static function scaleDimensions(array &$dimensions, $width = NULL, $height = NULL, $upscale = FALSE) {
  34. $aspect = $dimensions['height'] / $dimensions['width'];
  35. // Calculate one of the dimensions from the other target dimension,
  36. // ensuring the same aspect ratio as the source dimensions. If one of the
  37. // target dimensions is missing, that is the one that is calculated. If both
  38. // are specified then the dimension calculated is the one that would not be
  39. // calculated to be bigger than its target.
  40. if (($width && !$height) || ($width && $height && $aspect < $height / $width)) {
  41. $height = (int) round($width * $aspect);
  42. }
  43. else {
  44. $width = (int) round($height / $aspect);
  45. }
  46. // Don't upscale if the option isn't enabled.
  47. if (!$upscale && ($width >= $dimensions['width'] || $height >= $dimensions['height'])) {
  48. return FALSE;
  49. }
  50. $dimensions['width'] = $width;
  51. $dimensions['height'] = $height;
  52. return TRUE;
  53. }
  54. }