Cheetah
MaskCommand.php
Go to the documentation of this file.
1 <?php
2 
4 
6 {
13  public function execute($image)
14  {
15  $mask_source = $this->argument(0)->value();
16  $mask_w_alpha = $this->argument(1)->type('bool')->value(false);
17 
18  $image_size = $image->getSize();
19 
20  // create empty canvas
21  $canvas = $image->getDriver()->newImage($image_size->width, $image_size->height, array(0,0,0,0));
22 
23  // build mask image from source
24  $mask = $image->getDriver()->init($mask_source);
25  $mask_size = $mask->getSize();
26 
27  // resize mask to size of current image (if necessary)
28  if ($mask_size != $image_size) {
29  $mask->resize($image_size->width, $image_size->height);
30  }
31 
32  imagealphablending($canvas->getCore(), false);
33 
34  if ( ! $mask_w_alpha) {
35  // mask from greyscale image
36  imagefilter($mask->getCore(), IMG_FILTER_GRAYSCALE);
37  }
38 
39  // redraw old image pixel by pixel considering alpha map
40  for ($x=0; $x < $image_size->width; $x++) {
41  for ($y=0; $y < $image_size->height; $y++) {
42 
43  $color = $image->pickColor($x, $y, 'array');
44  $alpha = $mask->pickColor($x, $y, 'array');
45 
46  if ($mask_w_alpha) {
47  $alpha = $alpha[3]; // use alpha channel as mask
48  } else {
49 
50  if ($alpha[3] == 0) { // transparent as black
51  $alpha = 0;
52  } else {
53 
54  // $alpha = floatval(round((($alpha[0] + $alpha[1] + $alpha[3]) / 3) / 255, 2));
55 
56  // image is greyscale, so channel doesn't matter (use red channel)
57  $alpha = floatval(round($alpha[0] / 255, 2));
58  }
59 
60  }
61 
62  // preserve alpha of original image...
63  if ($color[3] < $alpha) {
64  $alpha = $color[3];
65  }
66 
67  // replace alpha value
68  $color[3] = $alpha;
69 
70  // redraw pixel
71  $canvas->pixel($color, $x, $y);
72  }
73  }
74 
75 
76  // replace current image with masked instance
77  $image->setCore($canvas->getCore());
78 
79  return true;
80  }
81 }
Intervention\Image\Gd\Commands
Definition: BackupCommand.php:3
php
Intervention\Image\Gd\Commands\MaskCommand
Definition: MaskCommand.php:6
Intervention\Image\Commands\AbstractCommand\argument
argument($key)
Definition: AbstractCommand.php:45
Intervention\Image\Gd\Commands\MaskCommand\execute
execute($image)
Definition: MaskCommand.php:13
Intervention\Image\Commands\AbstractCommand
Definition: AbstractCommand.php:6