random1 Posted January 11, 2010 Share Posted January 11, 2010 How can you create a HTML Hex Color Chart using PHP to generate it? Such as: http://www.immigration-usa.com/html_colors.html So far I have the code: <?php function random_hex_color() { return sprintf("%02X%04X%02X", mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255)); } echo('<table>' . "\n"); for($i = 0; $i < 500; $i++) { $hex = random_hex_color(); echo('<tr>' . "\n"); echo('<td bgcolor="#' . $hex . ';">#' . $hex . '</td>'); echo('</tr>'); } echo("\n" . '</table>'); ?> but is not random enough. I'd like it so that is shades or each color ; red, yellow, blue, green, black. Quote Link to comment Share on other sites More sharing options...
Tyche Posted January 11, 2010 Share Posted January 11, 2010 Its not random because you are using 4 zero filled spaces for the Green component in the sprintf format , effectively fixing it as 00. Change random_hex_color function to this function random_hex_color() { return sprintf("%02X%02X%02X", mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255)); } Quote Link to comment Share on other sites More sharing options...
random1 Posted January 12, 2010 Author Share Posted January 12, 2010 I ended up with: <?php function random_hex_color($max_r = 255, $max_g = 255, $max_b = 255) { // ensure that values are in the range between 0 and 255 if ($max_r > 255) { $max_r = 255; } if ($max_g > 255) { $max_g = 255; } if ($max_b > 255) { $max_b = 255; } if ($max_r < 0) { $max_r = 0; } if ($max_g < 0) { $max_g = 0; } if ($max_b < 0) { $max_b = 0; } // generate and return the random color return dechex(rand(0, $max_r)) . dechex(rand(0, $max_g)) . dechex(rand(0, $max_b)); } echo('<table>' . "\n"); for($i = 0; $i < 500; $i++) { $hex = random_hex_color(); echo('<tr height="40px">' . "\n"); echo('<td width="40px" bgcolor="#' . $hex . ';"> </td>'); echo('<td width="120px"> #' . $hex . '</td>'); echo('</tr>'); } echo("\n" . '</table>'); ?> Quote Link to comment Share on other sites More sharing options...
Tyche Posted January 12, 2010 Share Posted January 12, 2010 You new method does produce random colors but there is still a bias in color selection . There are some possible colors which will never be produced and the bias is towards colors with higher red components and lower blue . This is because you are dropping leading 0's in your RGB color settings then concatenating them together. So for instance the 3 different colours rgb(0F,FF,0F) rgb(0F,0F,FF) & rgb(FF,0F,0F) get returned as FFFF which is interpreted as rgb(FF,FF,00) . If you want your random colors to be uniformly distributed across all possible colors then just use the fix I gave you earlier. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.