Imagick::setCompressionQuality is used to set the compression quality for newly created images. It may have no effect on existing images.
Imagick::setCompressionQuality is used to set the compression quality for newly created images. It may have no effect on existing images.
function setCompressionQuality($image_path, $quality)
{
    $backgroundImagick = new \Imagick(realpath($image_path));

    $imagick = new \Imagick();
    $imagick->setCompressionQuality($quality);

    $imagick->newPseudoImage(
        640, // $backgroundImagick->getImageWidth(),
        480, // $backgroundImagick->getImageHeight(),
        'gradient:red-blue'
    );

    $imagick->compositeImage($backgroundImagick, \Imagick::COMPOSITE_ATOP, 0, 0);
    
    $imagick->setFormat("jpg");
    header("Content-Type: image/jpeg");
    echo $imagick->getImageBlob();
}