File indexing completed on 2025-01-26 05:29:14
0001 <?php 0002 0003 namespace Intervention\Image\Gd\Commands; 0004 0005 class MaskCommand extends \Intervention\Image\Commands\AbstractCommand 0006 { 0007 /** 0008 * Applies an alpha mask to an image 0009 * 0010 * @param \Intervention\Image\Image $image 0011 * @return boolean 0012 */ 0013 public function execute($image) 0014 { 0015 $mask_source = $this->argument(0)->value(); 0016 $mask_w_alpha = $this->argument(1)->type('bool')->value(false); 0017 0018 $image_size = $image->getSize(); 0019 0020 // create empty canvas 0021 $canvas = $image->getDriver()->newImage($image_size->width, $image_size->height, [0,0,0,0]); 0022 0023 // build mask image from source 0024 $mask = $image->getDriver()->init($mask_source); 0025 $mask_size = $mask->getSize(); 0026 0027 // resize mask to size of current image (if necessary) 0028 if ($mask_size != $image_size) { 0029 $mask->resize($image_size->width, $image_size->height); 0030 } 0031 0032 imagealphablending($canvas->getCore(), false); 0033 0034 if ( ! $mask_w_alpha) { 0035 // mask from greyscale image 0036 imagefilter($mask->getCore(), IMG_FILTER_GRAYSCALE); 0037 } 0038 0039 // redraw old image pixel by pixel considering alpha map 0040 for ($x=0; $x < $image_size->width; $x++) { 0041 for ($y=0; $y < $image_size->height; $y++) { 0042 0043 $color = $image->pickColor($x, $y, 'array'); 0044 $alpha = $mask->pickColor($x, $y, 'array'); 0045 0046 if ($mask_w_alpha) { 0047 $alpha = $alpha[3]; // use alpha channel as mask 0048 } else { 0049 0050 if ($alpha[3] == 0) { // transparent as black 0051 $alpha = 0; 0052 } else { 0053 0054 // $alpha = floatval(round((($alpha[0] + $alpha[1] + $alpha[3]) / 3) / 255, 2)); 0055 0056 // image is greyscale, so channel doesn't matter (use red channel) 0057 $alpha = floatval(round($alpha[0] / 255, 2)); 0058 } 0059 0060 } 0061 0062 // preserve alpha of original image... 0063 if ($color[3] < $alpha) { 0064 $alpha = $color[3]; 0065 } 0066 0067 // replace alpha value 0068 $color[3] = $alpha; 0069 0070 // redraw pixel 0071 $canvas->pixel($color, $x, $y); 0072 } 0073 } 0074 0075 0076 // replace current image with masked instance 0077 $image->setCore($canvas->getCore()); 0078 0079 return true; 0080 } 0081 }