ResizeCommand.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. <?php
  2. namespace Intervention\Image\Gd\Commands;
  3. class ResizeCommand extends \Intervention\Image\Commands\AbstractCommand
  4. {
  5. /**
  6. * Resizes image dimensions
  7. *
  8. * @param \Intervention\Image\Image $image
  9. * @return boolean
  10. */
  11. public function execute($image)
  12. {
  13. $width = $this->argument(0)->value();
  14. $height = $this->argument(1)->value();
  15. $constraints = $this->argument(2)->type('closure')->value();
  16. // resize box
  17. $resized = $image->getSize()->resize($width, $height, $constraints);
  18. // modify image
  19. $this->modify($image, 0, 0, 0, 0, $resized->getWidth(), $resized->getHeight(), $image->getWidth(), $image->getHeight());
  20. return true;
  21. }
  22. /**
  23. * Wrapper function for 'imagecopyresampled'
  24. *
  25. * @param Image $image
  26. * @param int $dst_x
  27. * @param int $dst_y
  28. * @param int $src_x
  29. * @param int $src_y
  30. * @param int $dst_w
  31. * @param int $dst_h
  32. * @param int $src_w
  33. * @param int $src_h
  34. * @return boolean
  35. */
  36. protected function modify($image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h)
  37. {
  38. // create new image
  39. $modified = imagecreatetruecolor($dst_w, $dst_h);
  40. // get current image
  41. $resource = $image->getCore();
  42. // preserve transparency
  43. $transIndex = imagecolortransparent($resource);
  44. if ($transIndex != -1) {
  45. $rgba = imagecolorsforindex($modified, $transIndex);
  46. $transColor = imagecolorallocatealpha($modified, $rgba['red'], $rgba['green'], $rgba['blue'], 127);
  47. imagefill($modified, 0, 0, $transColor);
  48. imagecolortransparent($modified, $transColor);
  49. } else {
  50. imagealphablending($modified, false);
  51. imagesavealpha($modified, true);
  52. }
  53. // copy content from resource
  54. $result = imagecopyresampled(
  55. $modified,
  56. $resource,
  57. $dst_x,
  58. $dst_y,
  59. $src_x,
  60. $src_y,
  61. $dst_w,
  62. $dst_h,
  63. $src_w,
  64. $src_h
  65. );
  66. // set new content as recource
  67. $image->setCore($modified);
  68. return $result;
  69. }
  70. }