Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resize PNGs with php Imagick preserving background

Tags:

php

image

imagick

I am trying to resize images using cropThumbnailImage. I use cropThumbnailImage as it resizes to the shorter length of the original image and crops the image on the longer side equally on both sides so that center portion of the image remains uncropped. This works fine for jpg images but for png images, the resized pngs get a black background.

Following is the code I use.

    $image = new \Imagick($src);

    // resize & crop
    $image->cropThumbnailImage($width, $height);

    // save new resized file
    $image->writeImage($dest);

Run this code for the following png image.

http://tuxpaint.org/stamps/stamps/animals/birds/cartoon/tux.png http://www.cs.csubak.edu/~mcabrera/CS211/transparent.png http://www.tcarms.com/media/assets/productPhotos/006_G2%20Contender/png/Pistol_12in_Ribbed_Blued_2720.png

The output image is resized as required but the png image gets black background.

Tried adding below lines from herebut did not work.

imagealphablending( $image, false );
imagesavealpha( $image, true );

There are other solutions out there in the web which achieve resizing of png images, but I did not find a solution that resizes image the way cropThumbnailImage does.

like image 851
Venkat Kotra Avatar asked Nov 25 '25 05:11

Venkat Kotra


1 Answers

Transparency is preserved using the following snippet:

$im = new Imagick($imgPath);
$im->setImageFormat('png');
$im->writeImage('/files/thumbnails/new_title.png');
like image 126
zeros-and-ones Avatar answered Nov 27 '25 20:11

zeros-and-ones



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!