Php IMG_FILTER_GRAYSCALE将透明像素转换为黑色

时间:2012-08-01 12:31:21

标签: php image grayscale imagefilter

我正在尝试将我的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在他们的部分问题中遇到了同样的问题,但从未特别回答过这个问题。

我希望有人可以帮忙解决这个问题!

如果它有帮助,我之前使用此片段转换为灰度,但它有同样的问题,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]);

    }

}

1 个答案:

答案 0 :(得分:2)

好吧,这主要是借来的..不太记得在哪里,但它应该有效:

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

希望有所帮助!