5

Please note that I have already read Generating a random hex color code with PHP and I got help from that question too. But my question is different to that question.

I am going to create 1000+ images with some text like below image.

enter image description here

Text color is always white. I need to generate background color randomly. I use following code to generate random color.

<?php

function random_color_part() {
    return str_pad( dechex( mt_rand( 0, 255 ) ), 2, '0', STR_PAD_LEFT);
}

function random_color() {
    return random_color_part() . random_color_part() . random_color_part();
}

echo random_color();

?>

This script generate light colors like white, light yellow, light blue too. I need to remove them. Because if the background color is also light colour it is hard to read the text.

So is there way to modify this code generate only dark colors?

Ranuka
  • 273
  • 3
  • 17
  • 1
    Depends on where your threshold for "light" is, but the closer your random number gets to 255, the brighter that color is going to be. Lowering that upper limit will get you darker colors. – rickdenhaan May 27 '17 at 17:14
  • @rickdenhaan That means if number is near to 255 it is light? Am I correct? So if I modify `mt_rand( 0, 255 )` to something like `mt_rand( 0, 150)` it always return dark colors? – Ranuka May 27 '17 at 17:16
  • 1
    Decrease the `255` constant. The lower - the darker. – Todor Simeonov May 27 '17 at 17:16

2 Answers2

5

May this is help you, random dark hex color in PHP

function random_color_part() {
    $dt = '';
    for($o=1;$o<=3;$o++)
    {
        $dt .= str_pad( dechex( mt_rand( 0, 127 ) ), 2, '0', STR_PAD_LEFT);
    }
    return $dt;
}

You only call random_color_part().

Bang Roy Han
  • 87
  • 1
  • 9
4

Light colors use high values. Lowering max argument for rand() should create darker colors, like this:

function random_color_part() {
    return str_pad( dechex( mt_rand( 0, 127 ) ), 2, '0', STR_PAD_LEFT);
}

But you will have to experiment with an exact threshold to get right colors.

You can use this snippet to check what happens with colors when you lower max color value (max).

function hex(i) {
  var hex = i.toString(16);
  if (hex.length == 1) {
    hex = '0' + hex;
  }
  return hex;
}

var max = 150;

for (var i = 0; i < max; i += 10) {
  var td = '';
  for (var j = 0; j < max; j += 10) {
    for (var k = 0; k < max; k += 10) {
      var color = '#' + hex(i) + hex(j) + hex(k);
      td += '<td style="background-color:' + color + ';">&nbsp;</td>';
    }
  }
  $('table').append('<tr>' + td + '</tr>');
}
table {
  border-collapse: collapse;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
</table>
mx0
  • 6,445
  • 12
  • 49
  • 54