Here is the code. I don't think watermarking the resized image on a new image changes anything.
namespace MyApp\Utils;
use Phalcon\Mvc\User\Component;
use \Phalcon\Image\Adapter\Imagick;
class Image extends Component
{
//Resize image to exact dimensions without stretching
public function resize($imgPath, $newWidth, $newHeight)
{
$image = new Imagick($imgPath);
$sourceHeight = $image->getHeight();
$sourceWidth = $image->getWidth();
if ($sourceHeight == $newHeight && $sourceWidth == $newWidth)
return;
$vFactor = $newHeight / $sourceHeight;
$hFactor = $newWidth / $sourceWidth;
$factor = min($vFactor, $hFactor);
$tempHeight = (int)round($sourceHeight * $factor);
$tempWidth = (int)round($sourceWidth * $factor);
$x0 = (int)(abs($newWidth - $tempWidth) / 2);
$y0 = (int)(abs($newHeight - $tempHeight) / 2);
$image->resize($tempWidth, $tempHeight, \Phalcon\Image::PRECISE);
$imageWithBackgroud = new Imagick('', $newWidth, $newHeight);
$imageWithBackgroud->background('#fff', 0)->watermark($image, $x0, $y0)->save($imgPath);
}
}