Rotates an image the specified number of degrees. Empty triangles left over from rotating the image are filled with the background color.
function rotateImage($image_path, $angle, $color, $crop)
{
    $imagick = new \Imagick(realpath($image_path));
    
    $originalWidth = $imagick->getImageWidth();
    $originalHeight = $imagick->getImageHeight();
    
    $imagick->rotateImage($color, $angle);
    
    if ($crop) {
        $imagick->setImagePage(
            $imagick->getimageWidth(),
            $imagick->getimageheight(),
            0,
            0
        );

        $imagick->cropImage(
            $originalWidth,
            $originalHeight,
            ($imagick->getimageWidth() - $originalWidth) / 2,
            ($imagick->getimageHeight() - $originalHeight) / 2
        );
    }

    header("Content-Type: image/jpg");
    echo $imagick->getImageBlob();
}