| 1: | <?php | 
| 2: |  | 
| 3: |  | 
| 4: |  | 
| 5: |  | 
| 6: |  | 
| 7: |  | 
| 8: |  | 
| 9: |  | 
| 10: |  | 
| 11: |  | 
| 12: |  | 
| 13: |  | 
| 14: |  | 
| 15: |  | 
| 16: |  | 
| 17: |  | 
| 18: |  | 
| 19: |  | 
| 20: |  | 
| 21: |  | 
| 22: |  | 
| 23: |  | 
| 24: | namespace WideImage\Operation; | 
| 25: |  | 
| 26: | use WideImage\Coordinate; | 
| 27: |  | 
| 28: |  | 
| 29: |  | 
| 30: |  | 
| 31: |  | 
| 32: |  | 
| 33: | class ApplyMask | 
| 34: | { | 
| 35: |  | 
| 36: |  | 
| 37: |  | 
| 38: |  | 
| 39: |  | 
| 40: |  | 
| 41: |  | 
| 42: |  | 
| 43: |  | 
| 44: | public function execute($image, $mask, $left = 0, $top = 0) | 
| 45: | { | 
| 46: | $left = Coordinate::fix($left, $image->getWidth(), $mask->getWidth()); | 
| 47: | $top  = Coordinate::fix($top, $image->getHeight(), $mask->getHeight()); | 
| 48: |  | 
| 49: | $width      = $image->getWidth(); | 
| 50: | $mask_width = $mask->getWidth(); | 
| 51: |  | 
| 52: | $height      = $image->getHeight(); | 
| 53: | $mask_height = $mask->getHeight(); | 
| 54: |  | 
| 55: | $result = $image->asTrueColor(); | 
| 56: |  | 
| 57: | $result->alphaBlending(false); | 
| 58: | $result->saveAlpha(true); | 
| 59: |  | 
| 60: | $srcTransparentColor = $result->getTransparentColor(); | 
| 61: |  | 
| 62: | if ($srcTransparentColor >= 0) { | 
| 63: | $destTransparentColor = $srcTransparentColor; | 
| 64: | } else { | 
| 65: | $destTransparentColor = $result->allocateColorAlpha(255, 255, 255, 127); | 
| 66: | } | 
| 67: |  | 
| 68: | for ($x = 0; $x < $width; $x++) { | 
| 69: | for ($y = 0; $y < $height; $y++) { | 
| 70: | $mx = $x - $left; | 
| 71: | $my = $y - $top; | 
| 72: |  | 
| 73: | if ($mx >= 0 && $mx < $mask_width && $my >= 0 && $my < $mask_height) { | 
| 74: | $srcColor = $image->getColorAt($x, $y); | 
| 75: |  | 
| 76: | if ($srcColor == $srcTransparentColor) { | 
| 77: | $destColor = $destTransparentColor; | 
| 78: | } else { | 
| 79: | $maskRGB = $mask->getRGBAt($mx, $my); | 
| 80: |  | 
| 81: | if ($maskRGB['red'] == 0) { | 
| 82: | $destColor = $destTransparentColor; | 
| 83: | } elseif ($srcColor >= 0) { | 
| 84: | $imageRGB          = $image->getRGBAt($x, $y); | 
| 85: | $level             = ($maskRGB['red'] / 255) * (1 - $imageRGB['alpha'] / 127); | 
| 86: | $imageRGB['alpha'] = 127 - round($level * 127); | 
| 87: |  | 
| 88: | if ($imageRGB['alpha'] == 127) { | 
| 89: | $destColor = $destTransparentColor; | 
| 90: | } else { | 
| 91: | $destColor = $result->allocateColorAlpha($imageRGB); | 
| 92: | } | 
| 93: | } else { | 
| 94: | $destColor = $destTransparentColor; | 
| 95: | } | 
| 96: | } | 
| 97: |  | 
| 98: | $result->setColorAt($x, $y, $destColor); | 
| 99: | } | 
| 100: | } | 
| 101: | } | 
| 102: |  | 
| 103: | return $result; | 
| 104: | } | 
| 105: | } | 
| 106: |  |