views:

293

answers:

2

I've got the code below to pull hex values from a database and create an image of that colour. There's over a thousand values, so it's looping to create an image for them all. It seems to work fine except it just keeps overwriting the first image (0.jpg) instead of creating new ones 0.jpg, 1.jpg 2.jpg etc. Any idea where I'm going wrong?

Oh yeah, I'm converting the hex to rgb in there too, that works fine.

<?php

    require ('connect.php');

    $sql = mysql_query("SELECT * FROM hex")
    or die(mysql_error());

    while($colors = mysql_fetch_array( $sql ))
        {

        $x = 0;

        $imgname = $x.".jpg";

        $color = $colors['value'];

         if (strlen($color) == 6)
          list($r, $g, $b) = array($color[0].$color[1],
                 $color[2].$color[3],
                 $color[4].$color[5]);

         $r = hexdec($r); $g = hexdec($g); $b = hexdec($b);

        header("Content-type: image/jpeg");
        $image = imagecreate( 720, 576 );
        imagecolorallocate($image,$r, $g, $b);
        imagejpeg($image, $imgname);
        imagedestroy($image);

        $x++;

        }
    ?>
+3  A: 

$x = 0; is executed in each iteration of the while loop. You need to move the initialization in front the loop.

VolkerK
+3  A: 

You just need to move $x = 0; to before the start of the loop.

There seem to be a few other things wrong, too

$x = 0;

while($colors = mysql_fetch_array( $sql ))
{
    $imgname = $x.".jpg";

    $color = $colors['value'];

    // Skip the whole lot if the colour is invalid
    if (strlen($color) != 6)
     continue;

    // No need to create an array just to call list()
    $r = hexdec($color[0].$color[1]);
    $g = hexdec($color[2].$color[3]);
    $b = hexdec($color[4].$color[5]);

    // There's no need to header() if you're writing to a file
    //header("Content-type: image/jpeg");
    $image = imagecreate( 720, 576 );
    $colour = imagecolorallocate($image, $r, $g, $b);

    // You don't actually fill the image with the colour
    imagefilledrectangle($image, 0, 0, 719, 575, $colour);

    imagejpeg($image, $imgname);
    imagedestroy($image);

    $x++;
}
Greg
Thanks for that, I'm still learning and cobbling things together a bit. I'll take those pointers onboard...
logic-unit