public function fitImageInCanvas(\Imagick $image, $width, $height)
{
$imageHeight = $image->getImageHeight();
$imageWidth = $image->getImageWidth();
if ($imageWidth > $width) {
$image->scaleImage($width, $height, true);
}
if ($imageHeight > $height) {
$image->scaleImage($width, $height, true);
}
$oldWidth = $image->getImageWidth();
$oldHeight = $image->getImageHeight();
#coords to center image inside fixed width/height canvas
$x = ($width - $oldWidth) / 2;
$y = ($height - $oldHeight) / 2;
#create new image with the user image centered
$newImage = new \Imagick();
$bgColor = $image->getImageFormat() == 'png' ? 'none' : 'white';
$newImage->newImage($width, $height, new \ImagickPixel($bgColor));
$newImage->compositeImage($image, \Imagick::COMPOSITE_OVER, $x, $y);
return $newImage;
}