Make part of the image transparent with IMagick / ImageMagick

I want to make part (or actually several parts) of an image transparent with IMagick so that I can use it as a mask for another image. I cannot figure out how to do this in a simple way.

So say the initial image is shown below, where X is any color:

XXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXXXXXXX 

Then I want some rectangular areas to be transparent (so this looks a bit like a punched card):

 XXXXXXXXXXXXX X XXXXXXXXXX X XXXX XXXX XXXXXXX XXXX XXXXXXXXXXXXX 

Does anyone know a good way to do this? Thanks.

+1
source share
1 answer

Figured it out.

 //Open your image and get its dimensions $image = new Imagick('image.png'); $height = $image->getImageHeight(); $width = $image->getImageWidth(); //Create a new transparent image of the same size $mask = new Imagick(); $mask->newImage($width, $height, new ImagickPixel('none')); $mask->setImageFormat('png'); //Draw onto the new image the areas you want to be transparent in the original $draw = new ImagickDraw(); $draw->setFillColor('black'); $draw->rectangle( 10,10,100,100 ); $mask->drawImage( $draw ); //Composite the images using Imagick::COMPOSITE_DSTOUT $image->compositeImage($mask, Imagick::COMPOSITE_DSTOUT, 0, 0, Imagick::CHANNEL_ALPHA); 
+1
source

All Articles