0

我有下面的代码从数据库中提取十六进制值并创建该颜色的图像。有一千多个值,所以它循环为它们创建一个图像。它似乎工作正常,只是它只是不断覆盖第一个图像(0.jpg)而不是创建新图像 0.jpg、1.jpg 2.jpg 等。知道我哪里出错了吗?

哦,是的,我也在其中将十六进制转换为 rgb,效果很好。

<?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++;

        }
    ?>
4

2 回答 2

3

$x = 0;在 while 循环的每次迭代中执行。您需要将初始化移到循环前面。

于 2009-12-03T09:42:05.163 回答
3

您只需要移动$x = 0;到循环开始之前。

似乎还有其他一些问题

$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++;
}
于 2009-12-03T09:42:07.943 回答