doupike2351
doupike2351
2013-12-24 06:20

imagefilter的半灰度()

已采纳

I know PHP's GD library can apply grayscale filter to an image, for example:

$img = imagecreatefrompng('test.png');
$img = imagefilter($img, IMG_FILTER_GRAYSCALE);
imagepng($img, 'test_updated.png');

Is there any method that can apply half of the grayscale effects (which is similar to CSS3's filter: grayscale(50%);) ?

I read from this answer, the grayscale filter is actually a reduction of R, G & B channel. Can I customize my own grayscale filter in PHP?

Reference: imagefilter()

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • duancheng3042 duancheng3042 8年前

    Is there any method that can apply half of the grayscale effects (which is similar to CSS3's filter: grayscale(50%);) ?

    Found a script something similar what you are looking for..

    <?php
    
    function convertImageToGrayscale($source_file, $percentage)
    {
        $outputImage = ImageCreateFromJpeg($source_file);
        $imgWidth    = imagesx($outputImage);
        $imgHeight   = imagesy($outputImage);
    
        $grayWidth  = round($percentage * $imgWidth);
        $grayStartX = $imgWidth-$grayWidth;
    
        for ($xPos=$grayStartX; $xPos<$imgWidth; $xPos++)
        {
            for ($yPos=0; $yPos<$imgHeight; $yPos++)
            {
                // Get the rgb value for current pixel
                $rgb = ImageColorAt($outputImage, $xPos, $yPos);
    
                // extract each value for r, g, b
                $rr = ($rgb >> 16) & 0xFF;
                $gg = ($rgb >> 8) & 0xFF;
                $bb = $rgb & 0xFF;
    
                // Get the gray Value from the RGB value
                $g = round(($rr + $gg + $bb) / 3);
    
                // Set the grayscale color identifier
                $val = imagecolorallocate($outputImage, $g, $g, $g);
    
                // Set the gray value for the pixel
                imagesetpixel ($outputImage, $xPos, $yPos, $val);
            }
        }
        return $outputImage;
    }
    
    $image = convertImageToGrayscale("otter.jpg", .25);
    
    header('Content-type: image/jpeg');
    imagejpeg($image);
    ?>
    

    See if that works. I found that here

    点赞 评论 复制链接分享