We are moving our forum in GitHub Discussions. For questions about Phalcon v3/v4 you can visit here and for Phalcon v5 here.

Resizing PNG image without loosing transparency

Does anyone know if it's possible to resize PNG image without loosing transparency with Imagick adapter?

Show us code, it doesnt have to be imagick adapter, it can be some things you doing with image itself which causing loosing transaprency.

edited Jan '16

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)

        $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);
edited Jan '16

But background can have, what happen if you comment 2 last lines ? I mean without background and watermark.

edited Jan '16


It seems you are right. The transparancy remains if I don't do watermarking on a new image part.

Do you know either how I could watermark without losing transparency in the original image (the newly created image with precise dimensions is transparent) or do some other trick to get precise image dimensions without stretching the image?