This is a quick post to share a utility I put together to extract all unique RGB hex colours from a given image.
My use case: I’m working on a project where a grid of clickable colour swatches needs to be generated. Due to limited space, it’s been difficult to settle on the the specific palette, knowing that the flexibility of an RGB or HSL colour picker isn’t an option. So I’ve been mocking up a few different arrangements of swatches in Photoshop, and experimenting with their layout.
At the same time, things like available space could change at any point, so between that and the need to adjust colours down the line, I don’t want to lay all the swatches out by hand and be tied to one arrangement. The layout has to be generative, and so I just need a raw list of colours to work with. The initial plan was to use the eye-dropper and pick out each one, pasting the hex values into a text file – but then I noticed I’d have to do that 60+ times for each revision, and thought: “Hello?! This is the 90s! Make the computer do it.”
The utility is very simple, and will just sift from the top-left pixel, traversing right, then to the next row – comparing against a running list to identify all the unique colours. Each colour is stored as a hex value (e.g. 0xBADA55) on a new line in the clipboard-able text data. You can then use some basic find-and-replace commands to get the list into a workable format for your needs.
If your image has gaps between swatches as mine does, and a background colour, this will be picked up as the first (or second) colour in the list – so you’ll likely want to trash that before going further. Another potential gotcha is the presence of anti-aliasing in your image, which could add unwanted in-between colours into the list. If you’re dealing with such a palette image, I would consider scaling the image down using a non-resampling algorithm – such as the ‘Nearest Neighbour’ mode in Photoshop. With some experimentation you should be left with only your core palette colours, ready for import into the extractor utility.