【问题标题】:Php IMG_FILTER_GRAYSCALE converting transparent pixels to blackPhp IMG_FILTER_GRAYSCALE 将透明像素转换为黑色
【发布时间】:2012-07-30 08:24:35
【问题描述】:

我正在尝试将我的 PNG 转换为灰度,并且它几乎可以在以下代码中正常工作:

$image = imagecreatefromstring(file_get_contents($this->image_dest."".$this->file_name));
imagefilter($image, IMG_FILTER_GRAYSCALE);
imagepng($image, $this->image_dest."".$this->file_name);

问题是,当图像具有一定透明度时,透明像素被渲染为黑色。我see there are others 在他们的部分问题中也有同样的问题,但从未针对这个问题专门回答过。

希望有人能帮忙解决这个问题!

如果有帮助,我以前使用这个 sn-p 转换为灰度,但它与 png 中的透明像素转换为黑色有同样的问题,我不确定 如何检测透明度并使用 imagecolorat 函数进行转换。

//Creates the 256 color palette
for ($c=0;$c<256;$c++){
    $palette[$c] = imagecolorallocate($new,$c,$c,$c);
}

//Creates yiq function
function yiq($r,$g,$b){
    return (($r*0.299)+($g*0.587)+($b*0.114));
} 

//Reads the origonal colors pixel by pixel 
for ($y=0;$y<$h;$y++) {

    for ($x=0;$x<$w;$x++) {

        $rgb = imagecolorat($new,$x,$y);
        $r = ($rgb >> 16) & 0xFF;
        $g = ($rgb >> 8) & 0xFF;
        $b = $rgb & 0xFF;

        //This is where we actually use yiq to modify our rbg values, and then convert them to our grayscale palette
        $gs = yiq($r,$g,$b);
        imagesetpixel($new,$x,$y,$palette[$gs]);

    }

}

【问题讨论】:

  • 嘿,我的朋友,我也遇到了这个问题。当我得到它时,我会发布一个解决方案。

标签: php image grayscale imagefilter


【解决方案1】:

好的,这主要是借来的。。不太记得在哪里,但应该可以:

        //$im is your image with the transparent background

        $width = imagesx($im);
        $height = imagesy($im);
        //Make your white background to overlay the original image on ($im)
        $bg = imagecreatetruecolor($width, $height);
        $white = imagecolorallocate($bg, 255, 255, 255);
        //Fill it with white
        imagefill($bg, 0, 0, $white);
        //Merge the two together
        imagecopyresampled($bg, $im, 0, 0, 0, 0, $width, $height, $width, $height);
        //Convert to gray-scale
        imagefilter($bg, IMG_FILTER_GRAYSCALE);

希望有帮助!

【讨论】:

  • 谢谢!我会试一试的!
  • 谢谢,我知道这是一个老问题,但答案对于同一问题来说是完美的。
猜你喜欢
  • 2011-03-26
  • 1970-01-01
  • 1970-01-01
  • 2016-06-14
  • 1970-01-01
  • 1970-01-01
  • 2013-04-29
  • 2021-10-20
  • 2013-01-09
相关资源
最近更新 更多