Mask an image with imagemagick

This is the task:

I have an image with the sizes 500×500. From this image I want to create a new Image, 200×200, where the former Image is cut from a circle. Everything outside the circle is supposed to be transparent. This can be nicely done with imagemagick:

//the base 500x500 image
$baseImage = 'img/base.jpg';

//the mask image, where the circle is transparent and everything outsite is black
$maskImage = 'img/kreis.png';

//step1: resize the base image to 200x200
$minFile = $path.'tmp/'.uniqid("tmp_").'.png';
$cmd = sprintf('convert %s -resize 200x200^ %s', $baseImage, $baseImage);
exec($cmd);

//step2: create a new temporary image in /tmp/ folder
$temp = 'tmp/' . uniqid("tmp_") . '.png' ;
touch( $temp );

//step3: place the mask over it
$cmd = sprintf( "convert %s %s -alpha off -compose CopyOpacity -composite %s", $baseImage, $maskImage, $temp );
exec( $cmd );

And that’s it.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.