Previous Article

PHP Colour lightness function

Next Article

Following on from my other 2 useful functions I thought I would show you another one which I have found useful for determining if a colour background needs a white or black text colour over the top.

I found this function a while back so can't take the credit for writing it myself, I have no idea to give the credit to but whoever you are thank you.

function get_brightness($hex) {
    // returns brightness value from 0 to 255
    // strip off any leading #
    $hex = str_replace('#', '', $hex);
    $c_r = hexdec(substr($hex, 0, 2));
    $c_g = hexdec(substr($hex, 2, 2));
    $c_b = hexdec(substr($hex, 4, 2));
    return (($c_r * 299) + ($c_g * 587) + ($c_b * 114)) / 1000;
}

The function takes your hex colour input and returns a value between 0 and 255. 0 is the darkest and 255 is lightest. I find a value around 80-90 is a good place to change the text colour from white to black, but this figure is worth experimenting with.

I hope this function helps you as much as it has me.

Avatar of Clive Walkden

Clive Walkden

Posted:

Latest Articles

Linux command line tools, installations etc

Linux

How to Install NordLayer VPN Client on Ubuntu 20.04 and Connect to a Virtual Network

A simple to follow installation guide for NordLayer VPN

MySQL usage, tweaks and learnings

MySQL

Mastering MySQL Database Imports on Linux

Learn efficient ways to import MySQL databases on Linux using the mysql command-line client. Explore the --source option and < operator for seamless data migration. Master MySQL imports on Linux with our comprehensive guide.

DevOps principles and tool usage

DevOps

Mastering SSH Key Conversions for DevOps

A guide to convert SSH keys from one version to another using Linux CLI