Ask your Symfony questions! Pay money and get answers fast! (more info)

Preserving PNG transparency with ecrop and sfThumbnail plugin Symfony


If you upload a PNG image to this site, and it has a transparent background, the transparent background becomes black (because the image is resized). [[LINK href=""]]There was once a PHP bug with partial transparency[[/LINK]], but it was fixed a long time ago. [[LINK href=""]]Alex Le[[/LINK]] has written about this issue. [[LINK href=""]]There are ways to perserve PNG transparency with PHP[[/LINK]] but I'm trying to stick with the code in Symfony plugins. I'm having the problem with both the [[LINK href=""]]eCrop[[/LINK]] plugin and [[LINK href=""]]sfThumbnail[[/LINK]].

I am curious, were these plugins stupidly written, or this more a matter of my server's settings? Is anyone else having any problems with transparent PNGs, when resized in either of these plugins?

The relevant output of "php -i":

GD Support => enabled
GD Version => 2.0 or higher
FreeType Support => enabled
FreeType Linkage => with freetype
FreeType Version => 2.3.5
T1Lib Support => enabled
GIF Read Support => enabled
GIF Create Support => enabled
JPG Support => enabled
PNG Support => enabled
WBMP Support => enabled
GetText Support => enabled

Symfony version 1.2.5.

Answers (3)


Nicolò Pignatelli answers:

Yes, Lawrence. Is a plugin issue.
eCrop, for example, uses <em>imagecopyresampled()</em> to crop an image. Well, this function do not support transparency, unless you apply a workaround.

Try using [[LINK href=""]]<em>sfImageTransformPlugin</em>[[/LINK]], instead; it allows for much more customization and configuration.

This is the workaround I was writing about before:

$t_im = imageCreateTrueColor($t_wd,$t_ht);
imagealphablending($t_im, false);
$transparent = imagecolorallocatealpha($t_im, 255, 255, 255, 0);
for($x=0;$x<$t_wd;$x++) {
for($y=0;$y<$t_ht;$y++) {
imageSetPixel( $t_im, $x, $y, $transparent );
imageCopyResampled($t_im, $o_im, 0, 0, 0, 0, $t_wd, $t_ht, $o_wd, $o_ht);
imagePNG($t_im, $image_name);

The alphablending must be off so the imagesavealpha can be true.

The double FORs is need to fix the problem with imagefill function that not support colors with alpha setted.


Andrei Dziahel answers:

I've recently implemented transparency preserving for pkImageConverterPlugin (only for GD engine) and planned to submit a patch to upstream. If you consider using this plugin, I can share a fix.


JuG answers:


If your application is running on on Linux (or Mac), I suggest you simply use "convert" !

function scale( $src_image, $dest_image, $width, $height )
$src = escapeshellarg( $src_image );
$dest = escapeshellarg( $dest_image );
$size = escapeshellarg( $width ).'x'.escapeshellarg( $height );

`convert -scale $size $src $dest`;

Whatever the image type you use as source or destination (PNG, GIF, JPEG, ...) it should work !