PHP:灰度jpgs,gifs,pngs ......还有alpha通道?

问题描述:

$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?

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

任何想法我能做什么,正确的灰度GIF和pngs与transperancy? 这个片段实际上运行良好,它将jpgs和pngs转换为灰度。 然而,GIF有点“马车” - 它们并不总是有效,它取决于图像。 有时会留下一些淡色。 此外,此代码段不适用于Alpha通道。 如果我转换带有透明度的gif或png,透明部分总会变黑。 p>

当然我要查询图像类型并在“灰度化”之后,我会设置正确的类型 再次。 p>

您有什么想法吗? p> div>

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);

For pngs a simple call to imagesavealpha() solves the problem of black pixels on the alpha channel, complete code:

$im = ImageCreateFromString(file_get_contents($source))    
imagefilter($im, IMG_FILTER_GRAYSCALE);
imagesavealpha($im,true);
imagepng( $im, $output );