Composites a set of images while respecting any page offsets and disposal methods. GIF, MIFF, and MNG animation sequences typically start with an image background and each subsequent image varies in size and offset. Returns a new Imagick object where each image in the sequence is the same size as the first and composited with the next image in the sequence.
Composites a set of images while respecting any page offsets and disposal methods. GIF, MIFF, and MNG animation sequences typically start with an image background and each subsequent image varies in size and offset. Returns a new Imagick object where each image in the sequence is the same size as the first and composited with the next image in the sequence.
function coalesceImages()
{
    $imagePaths = [
        "../imagick/images/lories/IMG_1599_480.jpg",
        "../imagick/images/lories/IMG_2561_480.jpg",
        "../imagick/images/lories/IMG_2837_480.jpg",
        "../imagick/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();
}