colour

PHP Logo

Color Sorting In PHP: Part 5

3rd November 2019 - 11 minutes read time

Since my last visit to this subject I have been thinking about how to represent a collection of random colors so that it looks sorted and that no information is lost during that process. I quickly realised that I needed to use all three aspects of the color space, which lends itself to generating 3D objects. Indeed, the red, green, blue color space is built around a cube so it can often be represented as a cube.

The hue, saturation, and value color space is built around the concept of a cylinder, which means that 2 of the axis lend themselves to a circumference of a circle (the hue) and the diameter of a circle (the saturation). This is an example of the polar coordinate system. We can therefore draw a circle using hue and saturation and the value can be used to represent a different aspect of the color space.

PHP Logo

Color Sorting In PHP

9th June 2018 - 14 minutes read time

Sorting colors is the sort of thing that you never really think about until you need to do it. Sorting a bunch of items by their color is useful in a number of applications, but the simplest is just to display items to the user in a more controlled manner. As it happens sorting with colors is a much more complex topic than I originally thought and required digging into quite a bit more maths than I expected.

Incidentally, there is a whole world of color maths that I didn't know existed until I started looking into this. It was worth learning about though.

Setting Up

To start with, I created a little Color class so that I could have a standard way of storing a color. This just takes the red, green and blue values for a color and allows a simple way of accessing those values.

PHP Logo

Desaturate Images With PHP

6th September 2011 - 5 minutes read time

To desaturate an image means to remove all non-greyscale colours from it, essentially creating a black and white version. To do this you can use the function imagecopymergegray(), which is part of the GD image library. This function is a little difficult to figure out, but what is does is sample one image into another and optionally changing the amount of colours that are kept during the sampling process. The function can be made to sample just a section of the image, or the whole thing. The parameters of the function are as follows.

PHP Logo

Generate A Random Colour With PHP

21st May 2008 - 1 minute read time

Here is a short bit of code to generate a random hexadecimal colour using PHP. Essentially you just create a random number between 0 (000000) and 10,000,000 (ffffff) and turn this into a hexadecimal number using the PHP function dechex.

$colour = rand(0, 10000000);
$colour = dechex($colour);

This can also be accomplished on a single line.

$colour = dechex(rand(0, 10000000));