2012-08-01 85 views
0

我试图让我的PNG图像转换成灰度,它几乎与此代码工作正常:腓IMG_FILTER_GRAYSCALE转换透明的像素为黑色

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

    } 

} 
+0

嘿,我的朋友,我也遇到了这个问题。当我得到它时,我会发布解决方案。 – Tim 2012-08-04 16:26:39

回答

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

希望帮助!

+0

谢谢!我会试一下! – scott 2012-08-05 08:51:09

+0

谢谢,我意识到这是一个古老的问题,但答案对于同一问题是完美的。 – solange 2015-10-19 06:35:23