duanla4959 2010-01-29 15:52
浏览 39
已采纳

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?

  • 写回答

2条回答 默认 最新

  • doukuai3822 2010-01-29 16:03
    关注

    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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决