Gabriel Stein
Gabriel Stein

Reputation: 478

How to mask an image with a composite but only where the color is black

I have a mask.png:

mask

And some other png image with the same dimensions:

image

Now I would like to mask the image with mask.png but only where the color is black on the mask image.

Desired result:

desired result

Is something like this possible with imagick if yes how?

Upvotes: 2

Views: 581

Answers (1)

emcconville
emcconville

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');

output.png

Upvotes: 2

Related Questions