0

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

問題は、画像に透明度がある場合、透明なピクセルが黒くレンダリングされることです。質問の一部で同じ質問をした人が他にもいるようですが、この問題について具体的に回答されたことはありません。

誰かがこれを手伝ってくれることを願っています!

それが役立つ場合は、以前にこのスニペットを使用してグレースケールに変換していましたが、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]);

    }

}
4

1 に答える 1

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

それが役立つことを願っています!

于 2012-08-04T16:47:02.093 に答える