scott
scott

Reputation: 1070

Php IMG_FILTER_GRAYSCALE converting transparent pixels to black

I am trying to get my PNGs converted into grayscale and it almost works properly with this code:

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

The problem is, when the image has some transparency, the transparent pixels are being rendered as black. I see there are others who have had the same question in part of their question, but it was never answered about this issue specifically.

I hope someone can help out with this!

If it helps, I was previously using this snippet to convert to greyscale, but it has the same problem with the transparent pixels in pngs being converted to black and I am not sure how to detect the transparency and convert it using the imagecolorat function.

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

    }

}

Upvotes: 0

Views: 1978

Answers (1)

Tango Bravo
Tango Bravo

Reputation: 3309

Okay, this was mostly borrowed.. Don't quite remember where, but it should work:

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

Hope that helps!

Upvotes: 2

Related Questions