2012-08-01 71 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