Cheetah
ResizeCanvasCommand.php
Go to the documentation of this file.
1 <?php
2 
4 
5 use \Intervention\Image\Point;
6 use \Intervention\Image\Size;
7 
9 {
16  public function execute($image)
17  {
18  $width = $this->argument(0)->type('digit')->required()->value();
19  $height = $this->argument(1)->type('digit')->required()->value();
20  $anchor = $this->argument(2)->value('center');
21  $relative = $this->argument(3)->type('boolean')->value();
22  $bgcolor = $this->argument(4)->value();
23 
24  $original_width = $image->getWidth();
25  $original_height = $image->getHeight();
26 
27  // check of only width or height is set
28  $width = is_null($width) ? $original_width : intval($width);
29  $height = is_null($height) ? $original_height : intval($height);
30 
31  // check on relative width/height
32  if ($relative) {
33  $width = $original_width + $width;
34  $height = $original_height + $height;
35  }
36 
37  // check for negative width/height
38  $width = ($width <= 0) ? $width + $original_width : $width;
39  $height = ($height <= 0) ? $height + $original_height : $height;
40 
41  // create new canvas
42  $canvas = $image->getDriver()->newImage($width, $height, $bgcolor);
43 
44  // set copy position
45  $canvas_size = $canvas->getSize()->align($anchor);
46  $image_size = $image->getSize()->align($anchor);
47  $canvas_pos = $image_size->relativePosition($canvas_size);
48  $image_pos = $canvas_size->relativePosition($image_size);
49 
50  if ($width <= $original_width) {
51  $dst_x = 0;
52  $src_x = $canvas_pos->x;
53  $src_w = $canvas_size->width;
54  } else {
55  $dst_x = $image_pos->x;
56  $src_x = 0;
57  $src_w = $original_width;
58  }
59 
60  if ($height <= $original_height) {
61  $dst_y = 0;
62  $src_y = $canvas_pos->y;
63  $src_h = $canvas_size->height;
64  } else {
65  $dst_y = $image_pos->y;
66  $src_y = 0;
67  $src_h = $original_height;
68  }
69 
70  // make image area transparent to keep transparency
71  // even if background-color is set
72  $transparent = imagecolorallocatealpha($canvas->getCore(), 255, 255, 255, 127);
73  imagealphablending($canvas->getCore(), false); // do not blend / just overwrite
74  imagefilledrectangle($canvas->getCore(), $dst_x, $dst_y, $dst_x + $src_w - 1, $dst_y + $src_h - 1, $transparent);
75 
76  // copy image into new canvas
77  imagecopy($canvas->getCore(), $image->getCore(), $dst_x, $dst_y, $src_x, $src_y, $src_w, $src_h);
78 
79  // set new core to canvas
80  $image->setCore($canvas->getCore());
81 
82  return true;
83  }
84 }
Intervention\Image\Gd\Commands
Definition: BackupCommand.php:3
php
Intervention\Image\Gd\Commands\ResizeCanvasCommand\execute
execute($image)
Definition: ResizeCanvasCommand.php:16
Intervention\Image\Gd\Commands\ResizeCanvasCommand
Definition: ResizeCanvasCommand.php:9
Intervention\Image\Commands\AbstractCommand\argument
argument($key)
Definition: AbstractCommand.php:45
Intervention\Image\Commands\AbstractCommand
Definition: AbstractCommand.php:6