Reputation: 478
I have a mask.png:
And some other png image with the same dimensions:
Now I would like to mask the image with mask.png but only where the color is black on the mask image.
Desired result:
Is something like this possible with imagick if yes how?
Upvotes: 2
Views: 581
Reputation: 24419
This is a really tricky question. Usually to isolate black colors, you would simply apply a SCREEN
composite.
$image->compositeImage($mask, Imagick::COMPOSITE_SCREEN, 0, 0);
But the mask in question already has an active alpha channel, so it may be possible that transparent black values exists, and cause undesired effects.
I would suggest rebuilding the mask as a new alpha color channel. That is to say, a black-n-white image where black represents a fully opaque pixel, and white is a fully transparent pixel. Then copy the rebuilt mask as the new alpha channel.
// Load resources.
$image = new Imagick('input.png');
$mask = new Imagick('mask.png');
// Create a white canvas.
$tempMask = new Imagick();
$tempMask->newPseudoImage($mask->width, $mask->height, 'XC:WHITE');
// Copy mask over canvas to replace transparent values.
$tempMask->compositeImage($mask, Imagick::COMPOSITE_ATOP, 0, 0);
// Invert colors.
$tempMask->negateImage(true);
// Copy temporary mask as the new alpha channel.
$image->compositeImage($tempMask, Imagick::COMPOSITE_COPYOPACITY, 0, 0);
// Save results.
$image->writeImage('output.png');
Upvotes: 2