Ex Nihilo

A Processing Sketch Blog

« | »

Generated Palettes from Photos

I’ve had a few requests now to share my code for grabbing generative palettes from photos. So as basic as it is, here’s my trick.

First I throw a set of photos into the sketch’s data folder, sequentially named 1.jpg through x.jpg (though I’ve since discovered Daniel Shiffman’s excellent directory listing functions that wouldn’t require me to touch the photo filenames). I choose a random image from this folder and load it into an off-screen buffer, then choose random pixels and load their colour values into a palette array.

// create buffer and setup palette variables
PGraphics buffer;
PImage paletteSource;
color[] palette;
int palettePhotos = 9;
int paletteCount = 24;

void setup() {

void loadPalette(int paletteCount) {

  // load in an image
  paletteSource = loadImage(int(random(1, palettePhotos)) + ".jpg");

  palette = new color[paletteCount];

  // load the image into the buffer
  buffer.image(paletteSource, 0, 0);

  for (int i = 0; i < paletteCount; i++) {
    int colorX = int(random(0, 300));
    int colorY = int(random(0, 300));
    color pick = buffer.get(colorX, colorY);
    palette[i] = pick;


That's it. Stupidly simple, but all the interesting colour combos I've posted on here in the past have been a direct result of this. Not every palette looks great, but if you're using interesting photos as the source, 7 or 8 times out of ten you get something workable.

A bit of code documentation: since I use both portrait and landscape photos, I decided to constrain the area I grab pixels from to a top left square of 300x300 pixels. You can adjust those values to suit, if needed.

You can control the number of colours you load in with the paletteCount variable, and the values ultimately end up in an array called palette[], which you can use sequentially:


or randomly:

 int paletteValue = int(random(1, paletteCount));
 obj.R = red(palette[paletteValue]);

Monday, September 14th, 2009 | Palettes | RSS 2.0

Leave a Reply

Powered by WP Hashcash