I've been working on saving swatches out as images using PHP, I made a head start on it and so far it's saving out the first colour, and last colour and black - but iterating the last colour for three blocks.
<?php
$colours = $_GET['c'];
$swatches = explode("|", $colours);
// Create image
$im = imagecreatetruecolor(120, 30);
foreach ($swatches as $key => $rgb_set)
{
if ($rgb_set=="") break;
list($r, $g, $b) = explode(",", $rgb_set);
$x_pos = (24 * $key);
$swatch = imagecolorallocate($im, $r, $g, $b);
imagefilledrectangle($im, $x_pos, 0, 24, 30, $swatch);
}
// Set the content type header
header('Content-Type: image/png');
// Save the image
imagepng($im);
imagedestroy($im);
Has anybody any idea what I'm doing wrong or how to resolve this so that it downloads all 5 swatches from a palette?
The issue appears to happen (at least in part) due to the hard-coded 24
value in your imagefilledrectangle
function call.
Instead of this (note the 24
):
imagefilledrectangle($im, $x_pos, 0, 24, 30, $swatch);
This:
imagefilledrectangle($im, $x_pos, 0, $x_pos+24, 30, $swatch);
So that the $x2
value of the imagefilledrectangle
continues to move along with the $x1
value that you have in your original code.
<?php
$colours = $_GET['c'];
$swatches = explode("|", $colours);
// Create image
$im = imagecreatetruecolor(120, 30);
foreach ($swatches as $key => $rgb_set)
{
if ($rgb_set == "") break;
list($r, $g, $b) = explode(",", $rgb_set);
$x_pos = (24 * $key);
$swatch = imagecolorallocate($im, $r, $g, $b);
imagefilledrectangle($im, $x_pos, 0, $x_pos+24, 30, $swatch);
}
// Set the content type header
header('Content-Type: image/png');
// Save the image
imagepng($im);
imagedestroy($im);
?>
Note:
This has been tested with the following URL query string:
?c=255,255,0|255,155,25|13,103,100|54,123,53|255,0,0