1

I wish to make part (or in fact, several parts) of an image transparent using IMagick, such that I can use it as a mask over a different image. I can't figure out any way of doing this in an simple fashion.

So say my starting image is represented as below, where X is any color:

XXXXXXXXXXXXX
XXXXXXXXXXXXX
XXXXXXXXXXXXX
XXXXXXXXXXXXX
XXXXXXXXXXXXX

Then I want to be able to make certain rectangular regions transparent (so it ends up a bit like a punch-card):

XXXXXXXXXXXXX
X  XXXXXXXXXX
X  XXXX  XXXX
XXXXXXX  XXXX
XXXXXXXXXXXXX

Does anyone know of a good way of doing this? Thanks.

PaulJNewell
  • 239
  • 3
  • 9
  • Would something like [this](http://stackoverflow.com/questions/1741488/using-a-transparent-png-as-a-clip-mask) work for you? – PinnyM Jan 07 '14 at 15:49
  • 1
    possible duplicate of [php imagick, how to make an area transparent](http://stackoverflow.com/questions/12349549/php-imagick-how-to-make-an-area-transparent) – AndreKR Aug 23 '15 at 05:37

1 Answers1

1

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); 
PaulJNewell
  • 239
  • 3
  • 9
  • Doesn't work for me, the `black` part of the mask just like transparent, none affection to the main image. – Suge Oct 27 '17 at 09:00