我正在尝试使用存储在MySQL数据库中的RGB或十六进制值创建一个带背景填充的.jpg文件。我想遍历记录并为我拥有的500个值创建一个.jpg,并用十六进制值命名它们。我找到了post similar to mine,但无法让它发挥作用。
我的数据库中的字段是hexValue(样本数据; B0171F),r,g,b。它存储了各自的价值。
我是php的新手,可以使用一些帮助。这是我试图使用的代码。
<?php
$username = "john";
$password = "myPassword";
$hostname = "localhost";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
//select a database to work with
$selected = mysql_select_db("mycolors",$dbhandle)
or die("Could not select Colors");
//execute the SQL query and return records
$sql = mysql_query("SELECT r, g, b FROM thex")
or die(mysql_error());
$x = 0;
while($row = mysql_fetch_array( $sql ))
{
$imgname = $x.".jpg";
$color = $row['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++;
}