Search code examples
phpimageimagemagickimagick

Imagick cut out parts of image and make them 100% transparent alpha


I have 2 images $main and $cutout_holes. $main is just any image while $cutout_holes is a black and white image that I want to use as a mask, cutting some holes in $main. I want all white (#ffffff) pixels of $cutout_holes to cut out fully transparent holes in $main. The below is what I have tried so far but it does not work at all.

Any suggestions are welcome

<?
$image = new Imagick();
$image->newImage(100, 100, new ImagickPixel("#222222"));

$image->compositeImage($main, Imagick::COMPOSITE_DEFAULT, 0, 0);
$image->compositeImage($cutout_holes, Imagick::COMPOSITE_DSTIN, 0, 0, Imagick::CHANNEL_ALPHA);

header('Content-type: image/png');
$image->setImageFormat('png');
echo $image;
?>

Solution

  • I believe the composite option(s) your thinking of are Screen & Multiply, but I also don't believe they'll give you the results your expecting. Generally in ImageMagick's documentation, masks are considered alpha-channel values/mattes (i.e. black = 0.0 = opaque, and white = 1.0 = transparent.) Simply flip, or negate, your $coutout_holes image, and apply it as the alpha channel.

    <?php
    $main = new Imagick('any.png');
    $cutout_holes = new Imagick('mask.png');
    
    // If original mask wasn't already negated, do it here.
    $cutout_holes->negateImage(FALSE);
    
    // Null any previous alpha states. Same as -alpha off
    $main->setImageAlphaChannel(Imagick::ALPHACHANNEL_DEACTIVATE);
    // (and/or) Drop matte state of mask. Same as +matte
    $cutout_holes->setImageMatte(FALSE);
    
    // Apply holes mask as the new alpha channel.
    $main->compositeImage($cutout_holes, Imagick::COMPOSITE_COPYOPACITY, 0, 0);
    

    Holes cut