ResizeCommand.php 2.3 KB

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