Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate a random DARK hex color code with PHP?

Tags:

php

random

colors

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?

like image 479
Ranuka Avatar asked Mar 10 '23 00:03

Ranuka


1 Answers

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().

like image 141
Bang Roy Han Avatar answered Mar 19 '23 01:03

Bang Roy Han