开发者

PHP: grayscale jpgs, gifs, pngs... also with alpha channels?

开发者 https://www.devze.com 2022-12-19 01:16 出处:网络
$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 act

$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 wo开发者_StackOverflow中文版rks 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?


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号