从具有不同颜色的图像中获取rgb值

时间:2016-09-22 01:20:36

标签: php image argb

以下代码(主要来自此处)将以图像颜色创建文本,只要图像是纯色。我希望能够在图像不是一种颜色时创建文本,就像它是一个砖的图像,其中表面具有不同的,随机的颜色。我在这里找到了一些代码,其中可以读入源的每个像素,但是然后它合并那些并且没有给出真正的再现。这可能>

    $im = imagecreatefrompng('green.png');
    $rgb = imagecolorat($im, 4,4);
    $r = ($rgb >> 16) & 0xFF;
    $g = ($rgb >> 8) & 0xFF;
    $b = $rgb & 0xFF;

    echo '<div style="font-size:60px;color:rgb(' .$r .','.$g.','.$b.')">Text in color of the Image</div>';

1 个答案:

答案 0 :(得分:0)

取代一个样本,我取了10个样本并平均颜色。您可以尝试更多样品。

        <?php 
    $im = imagecreatefrompng('images/green.png');

    $width = imagesx($im);
    $height = imagesy($im);        

    $hpart = round($width/5);  // divide image in five columns
    $vpart = round($height/2); // divide image in two rows


    $r = 0;
    $g = 0;
    $b = 0;

    $rarr = array();
    $garr = array();
    $barr = array();


    for($i=0; $i<5; $i++) {
        $sampleh = round($hpart/2) + ($hpart*$i);
        $samplev = round($vpart/2);

        $rgb = imagecolorat($im, $sampleh,$samplev);
        $r += ($rgb >> 16) & 0xFF;
        $g += ($rgb >> 8) & 0xFF;
        $b += $rgb & 0xFF;        

        $rarr[] = ($rgb >> 16) & 0xFF;
        $garr[] = ($rgb >> 8) & 0xFF;
        $barr[] = $rgb & 0xFF;

    }

    for($i=0; $i<5; $i++) {
        $sampleh = round($hpart/2) + ($hpart*$i);
        $samplev = round($vpart/2) + $vpart;

        $rgb = imagecolorat($im, $sampleh,$samplev);
        $r += ($rgb >> 16) & 0xFF;
        $g += ($rgb >> 8) & 0xFF;
        $b += $rgb & 0xFF;     

        $rarr[] = ($rgb >> 16) & 0xFF;
        $garr[] = ($rgb >> 8) & 0xFF;
        $barr[] = $rgb & 0xFF;            

    }        

    $r = round($r/10);
    $g = round($g/10);
    $b = round($b/10);

   // echo "$r , $g, $b <br/>\n";        

    //        $rgb = imagecolorat($im, 4,4);
    //        $r = ($rgb >> 16) & 0xFF;
    //        $g = ($rgb >> 8) & 0xFF;
    //        $b = $rgb & 0xFF;
    //        echo "$r , $g, $b <br/>\n";    

    echo "<div> <img src='images/green.png' border=1 /></div><br/>\n";
    echo '<div style="font-size:60px;color:rgb(' .$r .','.$g.','.$b.')">Text in color of the Image</div>';

    $text = "Text in color of the Image";
    $coloredText = "";
    $j = 0;

    for($i=0; $i<strlen($text); $i++) {
        $coloredText .= '<span style="color:rgb(' .$rarr[$j] .','.$garr[$j].','.$barr[$j].')">'.$text[$i].'</span>';
        $j++;
        if($j === 10) {
            $j=0;
        }
    }

    echo "<div style='font-size:60px;'>$coloredText </div>\n";
    ?>
相关问题