phpphp-gd

Multiple degree color in PHP GD


I'm trying to make a degree color image in the PHP GD library. I just made a simple code that works fine with 2 colors, but, if I put more than 2, it makes something strange.

My code:

function gradientfilledrectangle ( $image, $x1, $y1, $x2, $y2, $colors ) {

    if ( $x1 > $x2 || $y1 > $y2 ) { return 0; }

    $steps = $y2 - $y1;
    $s = 0;
    $stop = 0;

    $st = $steps / ( count ( $colors ) - 1 );

    for ( $i = 0; $i < ( count ( $colors ) - 1 ); $i++ ) {

        for ( ; $s < ( $st + $stop ); $s++ ) {

            $r = abs ( round ( $colors [$i] [0] - ( ( ( $colors [$i] [0] - $colors [$i + 1] [0] ) / $st ) * $s ) ) );
            $g = abs ( round ( $colors [$i] [1] - ( ( ( $colors [$i] [1] - $colors [$i + 1] [1] ) / $st ) * $s ) ) );
            $b = abs ( round ( $colors [$i] [2] - ( ( ( $colors [$i] [2] - $colors [$i + 1] [2] ) / $st ) * $s ) ) );

            $color = imagecolorallocate ( $image, $r, $g, $b );

            imagefilledrectangle ( $image, $x1, $y1 + $s, $x2, $y1 + $s + 1, $color );

        }

        $stop += $st;

    }

    return 1;

}

and call:

list ( $w, $h ) = array ( 600, 600 );

$im = imagecreatetruecolor ( $w, $h );

$degree = array (
    array ( 200, 100, 0 ),
    array ( 0, 100, 200 ),
    array ( 100, 200, 0 )
);

if ( count ( $degree ) < 2 ) {

    imagefilledrectangle ( $im, 0, 0, $w, $h, imagecolorallocate ( $im, $degree [0] [0], $degree [0] [1], $degree [0] [2] ) );

} else {

    gradientfilledrectangle ( $im, 0, 0, $w, $h, $degree );

}

header ( 'Content-Type: image/jpeg' );

imagejpeg ( $im, null, 100 );
imagedestroy ( $im );

Hope you can help me,

Thanks a lot.


Solution

  • Well, already i solved the question. I forgot to substract the $stop value to color:

    $r = abs ( round ( $colors [$i] [0] - ( ( ( $colors [$i] [0] - $colors [$i + 1] [0] ) / $st ) * ( $s - $stop ) ) ) );
    $g = abs ( round ( $colors [$i] [1] - ( ( ( $colors [$i] [1] - $colors [$i + 1] [1] ) / $st ) * ( $s - $stop ) ) ) );
    $b = abs ( round ( $colors [$i] [2] - ( ( ( $colors [$i] [2] - $colors [$i + 1] [2] ) / $st ) * ( $s - $stop ) ) ) );
    

    This makes the apropiate calculating of the color. Thanks a lot to everyone.