Can I swap colors in image using GD library in PHP?

前端 未结 8 1512
遇见更好的自我
遇见更好的自我 2020-12-03 08:18

I got the image like this (it\'s a graph):


(source: kitconet.com)

I want to change the colours, so the white is black, the graph line is li

8条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-03 08:51

    The slow but sure approach, iterating over every pixel.

    function ReplaceColour($img, $r1, $g1, $b1, $r2, $g2, $b2)
    {
        if(!imageistruecolor($img))
            imagepalettetotruecolor($img);
        $col1 = (($r1 & 0xFF) << 16) + (($g1 & 0xFF) << 8) + ($b1 & 0xFF);
        $col2 = (($r2 & 0xFF) << 16) + (($g2 & 0xFF) << 8) + ($b2 & 0xFF);
    
        $width = imagesx($img); 
        $height = imagesy($img);
        for($x=0; $x < $width; $x++)
            for($y=0; $y < $height; $y++)
            {
                $colrgb = imagecolorat($img, $x, $y);
                if($col1 !== $colrgb)
                    continue; 
                imagesetpixel ($img, $x , $y , $col2);
            }   
    }
    

提交回复
热议问题