Problems resizing transparent PNG image

Hello,

I am creating an application that will help me resize images quickly.

Some of the images I wanted to resize in in PNG format, with alpha channel, but when I resize using imagecopyresampled, the output image is not ahh, transparent anymore.

Any ideas please?

This is the way this application work: This application opens the source image, and calculate the destination size, create a new true color image, and then imagecopyresampled to the destination image resource, then write to file.

I’m not sure why none of it’s transparent, but it really doesn’t surprise me. You don’t have much control over image resizing and you need to do it in a decent graphics package if you want to keep the quality.

imagealphablending()
http://www.php.net/manual/en/function.imagealphablending.php
imagesavealpha()
http://www.php.net/manual/en/function.imagesavealpha.php

If you want to resize a png-24 image and preserve the alpha channel you need to set imagealphablending($im_dest, false) on the destination image just after creating it with imagecreatetruecolor() and do a imagesavealpha($im_dest, true) on it before saving it:


<?php

$im = ImageCreateFromPNG('redfade.png');

$im_dest = imagecreatetruecolor (500, 300);
imagealphablending($im_dest, false);

imagecopyresampled($im_dest, $im, 0, 0, 0, 0, 300, 300, 500, 300);

imagesavealpha($im_dest, true);
imagepng($im_re, 'small_redfade.png');

?>

Oh, thank you very much!

Looks like imagesavealpha is the key. I’ll try it.

For all of you looking for a way to transform images on the fly, you might want to check the open-source project Asido: there are a lot of useful features ([URL=“http://www.asido.info/about/features/”]http://www.asido.info/about/features/), including [URL=“http://www.asido.info/about/features/#resize”]various types of image resize - like fit resize (resize if bigger) and frame resize (force-fit), [URL=“http://www.asido.info/about/features/#watermark”]watermarking, [URL=“http://www.asido.info/about/features/#copy”]image copy, [URL=“http://www.asido.info/about/features/#crop”]cropping, etc. There is no problem working w/ transparent images at all - check the examples on the [URL=“http://asido.info”]Asido website. Also, it can use various platforms: not only GD but ImageMagick too (either via shell or via any of the php extensions like php_magickwand.dll or php_imagick.dll). Here’s the list of drivers: [URL=“http://www.asido.info/about/drivers/”]http://www.asido.info/about/drivers/