doupike2351 2013-12-24 06:20
浏览 78
已采纳

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 2013-12-24 06:42
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Excel发现不可读取的内容
  • ¥15 UE5#if WITH_EDITOR导致打包的功能不可用
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?
  • ¥15 电磁场的matlab仿真
  • ¥15 mars2d在vue3中的引入问题
  • ¥50 h5唤醒支付宝并跳转至向小荷包转账界面
  • ¥15 算法题:数的划分,用记忆化DFS做WA求调
  • ¥15 chatglm-6b应用到django项目中,模型加载失败
  • ¥15 CreateBitmapFromWicBitmap内存释放问题。