MaskCommand.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. <?php
  2. namespace Intervention\Image\Gd\Commands;
  3. use Intervention\Image\Commands\AbstractCommand;
  4. class MaskCommand extends AbstractCommand
  5. {
  6. /**
  7. * Applies an alpha mask to an image
  8. *
  9. * @param \Intervention\Image\Image $image
  10. * @return boolean
  11. */
  12. public function execute($image)
  13. {
  14. $mask_source = $this->argument(0)->value();
  15. $mask_w_alpha = $this->argument(1)->type('bool')->value(false);
  16. $image_size = $image->getSize();
  17. // create empty canvas
  18. $canvas = $image->getDriver()->newImage($image_size->width, $image_size->height, [0,0,0,0]);
  19. // build mask image from source
  20. $mask = $image->getDriver()->init($mask_source);
  21. $mask_size = $mask->getSize();
  22. // resize mask to size of current image (if necessary)
  23. if ($mask_size != $image_size) {
  24. $mask->resize($image_size->width, $image_size->height);
  25. }
  26. imagealphablending($canvas->getCore(), false);
  27. if ( ! $mask_w_alpha) {
  28. // mask from greyscale image
  29. imagefilter($mask->getCore(), IMG_FILTER_GRAYSCALE);
  30. }
  31. // redraw old image pixel by pixel considering alpha map
  32. for ($x=0; $x < $image_size->width; $x++) {
  33. for ($y=0; $y < $image_size->height; $y++) {
  34. $color = $image->pickColor($x, $y, 'array');
  35. $alpha = $mask->pickColor($x, $y, 'array');
  36. if ($mask_w_alpha) {
  37. $alpha = $alpha[3]; // use alpha channel as mask
  38. } else {
  39. if ($alpha[3] == 0) { // transparent as black
  40. $alpha = 0;
  41. } else {
  42. // $alpha = floatval(round((($alpha[0] + $alpha[1] + $alpha[3]) / 3) / 255, 2));
  43. // image is greyscale, so channel doesn't matter (use red channel)
  44. $alpha = floatval(round($alpha[0] / 255, 2));
  45. }
  46. }
  47. // preserve alpha of original image...
  48. if ($color[3] < $alpha) {
  49. $alpha = $color[3];
  50. }
  51. // replace alpha value
  52. $color[3] = $alpha;
  53. // redraw pixel
  54. $canvas->pixel($color, $x, $y);
  55. }
  56. }
  57. // replace current image with masked instance
  58. $image->setCore($canvas->getCore());
  59. return true;
  60. }
  61. }