How to use Imagick to merge and mask images?

So, finally, this should do what you need:

Original image:

http://i.stack.imgur.com/b7seR.png

Opacity mask:

enter image description here

Overlay:

http://i.stack.imgur.com/3ulkM.png

Output:

enter image description here

The code:

<?php
$base = new Imagick('U0R4F.png');
$mask = new Imagick('mask.png');
$over = new Imagick('3ulkM.png');

// Setting same size for all images
$base->resizeImage(274, 275, Imagick::FILTER_LANCZOS, 1);

// Copy opacity mask
$base->compositeImage($mask, Imagick::COMPOSITE_DSTIN, 0, 0, Imagick::CHANNEL_ALPHA);

// Add overlay
$base->compositeImage($over, Imagick::COMPOSITE_DEFAULT, 0, 0);

$base->writeImage('output.png');
header("Content-Type: image/png");

echo $base;
?>

I hope it’s right now!
Note: In your example it looks like you downscaled the base image, which I didn’t (my goal is just to show how the masking is done).

Leave a Comment