首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用imagefilter()

用imagefilter()
EN

Stack Overflow用户
提问于 2013-12-24 06:20:06
回答 1查看 500关注 0票数 1

我知道PHP的GD库可以将灰度过滤器应用于图像,例如:

代码语言:javascript
复制
$img = imagecreatefrompng('test.png');
$img = imagefilter($img, IMG_FILTER_GRAYSCALE);
imagepng($img, 'test_updated.png');

是否有任何方法可以应用一半的灰度效应(类似于CSS3 3的filter: grayscale(50%);)?

我从这个回答上读到,灰度滤波器实际上是R,G&B通道的减少。我可以在PHP中自定义我自己的灰度过滤器吗?

参考资料:imagefilter()

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-12-24 06:42:37

是否有任何方法可以应用一半的灰度效应(类似于CSS3 3的过滤器:灰度(50%);)?

找到了一个和你想要的剧本相似的东西。

代码语言:javascript
复制
<?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);
?>

看看能不能。我发现这里

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20755900

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档