ResizeCanvasCommand.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. <?php
  2. namespace Intervention\Image\Gd\Commands;
  3. class ResizeCanvasCommand extends \Intervention\Image\Commands\AbstractCommand
  4. {
  5. /**
  6. * Resizes image boundaries
  7. *
  8. * @param \Intervention\Image\Image $image
  9. * @return boolean
  10. */
  11. public function execute($image)
  12. {
  13. $width = $this->argument(0)->type('digit')->required()->value();
  14. $height = $this->argument(1)->type('digit')->required()->value();
  15. $anchor = $this->argument(2)->value('center');
  16. $relative = $this->argument(3)->type('boolean')->value();
  17. $bgcolor = $this->argument(4)->value();
  18. $original_width = $image->getWidth();
  19. $original_height = $image->getHeight();
  20. // check of only width or height is set
  21. $width = is_null($width) ? $original_width : intval($width);
  22. $height = is_null($height) ? $original_height : intval($height);
  23. // check on relative width/height
  24. if ($relative) {
  25. $width = $original_width + $width;
  26. $height = $original_height + $height;
  27. }
  28. // check for negative width/height
  29. $width = ($width <= 0) ? $width + $original_width : $width;
  30. $height = ($height <= 0) ? $height + $original_height : $height;
  31. // create new canvas
  32. $canvas = $image->getDriver()->newImage($width, $height, $bgcolor);
  33. // set copy position
  34. $canvas_size = $canvas->getSize()->align($anchor);
  35. $image_size = $image->getSize()->align($anchor);
  36. $canvas_pos = $image_size->relativePosition($canvas_size);
  37. $image_pos = $canvas_size->relativePosition($image_size);
  38. if ($width <= $original_width) {
  39. $dst_x = 0;
  40. $src_x = $canvas_pos->x;
  41. $src_w = $canvas_size->width;
  42. } else {
  43. $dst_x = $image_pos->x;
  44. $src_x = 0;
  45. $src_w = $original_width;
  46. }
  47. if ($height <= $original_height) {
  48. $dst_y = 0;
  49. $src_y = $canvas_pos->y;
  50. $src_h = $canvas_size->height;
  51. } else {
  52. $dst_y = $image_pos->y;
  53. $src_y = 0;
  54. $src_h = $original_height;
  55. }
  56. // make image area transparent to keep transparency
  57. // even if background-color is set
  58. $transparent = imagecolorallocatealpha($canvas->getCore(), 255, 255, 255, 127);
  59. imagealphablending($canvas->getCore(), false); // do not blend / just overwrite
  60. imagefilledrectangle($canvas->getCore(), $dst_x, $dst_y, $dst_x + $src_w - 1, $dst_y + $src_h - 1, $transparent);
  61. // copy image into new canvas
  62. imagecopy($canvas->getCore(), $image->getCore(), $dst_x, $dst_y, $src_x, $src_y, $src_w, $src_h);
  63. // set new core to canvas
  64. $image->setCore($canvas->getCore());
  65. return true;
  66. }
  67. }