function coalesceImages()
{
    $imagePaths = [
        "../public/images/lories/IMG_1599_480.jpg",
        "../public/images/lories/IMG_2561_480.jpg",
        "../public/images/lories/IMG_2837_480.jpg",
        "../public/images/lories/IMG_4023_480.jpg",
    ];

    $canvas = new Imagick();
    foreach ($imagePaths as $imagePath) {
        $canvas->readImage(realpath($imagePath));
        $canvas->setImageDelay(100);
    }
    $canvas->setImageFormat('gif');
    
    $finalImage = $canvas->coalesceImages();
    $finalImage->setImageFormat('gif');
    $finalImage->setImageIterations(0); //loop forever
    $finalImage->mergeImageLayers(\Imagick::LAYERMETHOD_OPTIMIZEPLUS);

    header("Content-Type: image/gif");
    echo $finalImage->getImagesBlob();
}