IMagick is a native PHP extension to create and modify images using the ImageMagick API. ImageMagick Studio LLC did not write nor does it maintain the IMagick extension, however, IMagick users are welcome to discuss the extension here.
<?php
// Create a new image with everything transparent apart from the selected colour.
// This image must be saved as a png due to the transparency.
exec("convert $img -matte \( +clone -fuzz 20% -transparent rgb\(38,134,71\) \) -compose DstOut -composite temp.png");
// Another tempory image is made from the original but completely grey.
exec("convert $img -colorspace Gray grey_background.jpg");
// The two images are combined and flattened into one image.
exec("convert grey_background.jpg -page +0+0 temp.png -flatten output.jpg");
// The tempory images are deleted.
unlink ('output_hat.png');
unlink ('grey_background.jpg');
?>
The code is quite old and could probably be improved.