【问题标题】:How to isolate only one colour on image with PHP?如何使用 PHP 在图像上仅隔离一种颜色?
【发布时间】:2011-04-14 00:54:17
【问题描述】:

是否可以在图像中只留下(隔离)一种颜色? 目前我对绿色感兴趣:005d00

【问题讨论】:

    标签: php imagick gd2


    【解决方案1】:

    您可以使用 gd 的 imagecolorat() 函数。
    只需遍历每个像素,检查它是否是您想要的颜色,否则 set 将其设置为黑色或白色或任何您想要使用的颜色。

    这是一个工作示例:

    function colorEquals($rgb_color, $hex_color)
    {
        $r = ($rgb_color >> 16) & 0xFF;
        $g = ($rgb_color >> 8) & 0xFF;
        $b = $rgb_color & 0xFF;
    
    
        list($hr, $hg, $hb) = sscanf($hex_color, '%2s%2s%2s');
        $hr = hexdec($hr);
        $hg = hexdec($hg);
        $hb = hexdec($hb);
    
        return $r == $hr && $g == $hg && $b == $hb;
    }
    
    $width = 300;
    $height = 300;
    
    // create 300x300 image
    $img = imagecreatetruecolor($width, $height);
    // fill grey
    $color = imagecolorallocate($img, 127, 127, 127);
    imagefill($img, 0, 0, $color);
    
    // set a square of pixels to 005d00
    $your_color = imagecolorallocate($img, 0, 93, 0);
    imagefilledrectangle($img, 10, 10, 100, 100, $your_color);
    
    $white = imagecolorallocate($img, 255, 255, 255);
    
    for($x = 0; $x < $width; ++$x)
    {
        for($y = 0; $y < $height; ++$y)
        {
            $color = imagecolorat($img, $x, $y);
            if(!colorEquals($color, '005d00'))
            {
                // set it to white
                imagesetpixel($img, $x, $y, $white);
            }
        }
    }
    
    // output
    header('Content-type: image/png');
    imagepng($img);
    

    【讨论】:

    • 大图像会非常耗时。感谢您的回复,但我宁愿考虑从图像中删除所有蓝色和红色。但是不知道怎么弄。
    • @mickula:它不可能比这更有效(也许通过一些恒定因素 - 但不是任何渐近显着的数量)。想一想 - 每个像素都必须至少迭代一次以保持颜色或更改颜色,除非您使用的是我们不知道的某种图像格式,它提供了额外的信息。
    • `$average = new Imagick("duzykevarska.png"); header("内容类型:图片/png"); $clut = 新的想象(); $clut->newImage(1, 1, new ImagickPixel("rgb(0,93,0)")); $average->opaquePaintImage(new ImagickPixel("rgb(0,93,0)"), "white", 255, true);回声$平均; `
    • @mickula:我无法测试您发布的代码,因为我没有 Imagick。这就是你问题的答案吗? (如果是这样,您应该将其发布为答案并将其标记为这样)或者它是否有效,但没有执行?
    【解决方案2】:

    你可以通过命令行使用 ImageMagick 来做到这一点:

    convert original.png -matte ( +clone -fuzz 1 -transparent #005d00 ) -compose DstOut -composite isolated.png
    

    -fuzz 命令可以从颜色中获取百分比变化,如果是特定的,则删除模糊。

    () 括号需要在 bash shell \(\) 等中转义。

    【讨论】:

      猜你喜欢
      • 2010-11-01
      • 2015-12-19
      • 1970-01-01
      • 2014-02-28
      • 2012-08-24
      • 2021-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多