tags:

views:

35

answers:

1

Hey guys,

$im = ImageCreateFromString(file_get_contents($source_file));
ImageFilter($im, IMG_FILTER_GRAYSCALE);

any idea what i could do, to properly grayscale gifs and pngs with transperancy? This snippet actually works good, it transforms jpgs and pngs to grayscale. However gifs are a little bit "buggy" - they don't always work, it depends on the image. Sometimes there are a few pale colors left in them. Moreover this snippet doesn't work with alpha-channels. If i convert a gif or a png with transparancy the transparent parts always get blackened.

Of course im querying the image-type and after "grayscaling" it, i'll set the proper type again.

Have you any ideas?

+1  A: 

This code should preserve the alpha, but it's slower than imagefilter:

$im = ImageCreateFromString(file_get_contents($source_file));

$width=imagesx();
$height=imagesy();
for($x=0;$x<$width;$x++)
 for($y=0;$y<$height;$y++)
 {
  $rgb=imagecolorsforindex($im,imagecolorat($im,$x,$y));
  $average=ceil(($rgb["red"]+$rgb["green"]+$rgb["blue"])/3);
  imagesetpixel($im,$x,$y,imagecolorallocatealpha($im,$average,$average,$average,$rgb['alpha']));
 }

If you still have problems try to write this after the image creation (before the $width=..):

imagesavealpha($im,true);
mck89
thank you! without imagesavealpha nothing changes at all. If i set it, only png's alphachannel works. Gif transparency still get blackened. Moreover some gifs and pngs don't get properly grayscaled. Any more ideas.