Image manipulation with Processing

The purpose of this site is to share a few things I’ve found with others who will, hopefully, find them interesting and/or useful. The very first article is a good example of what will follow. Here is the problem I had a few minutes ago: I had just installed a new theme on my blog and I wanted to customize the header image. This was the original image:

Original theme header
Original theme header

I wanted to use the image of an arduino board instead. Using GIMP, I easily managed to modify a photo I found online, so that it had the right size. I also converted it to black & white.

New header, modified in GIMP
New header, modified in GIMP

So far so good… The problem is that I’m not an expert user of GIMP, so I hit a wall trying to convert this image from black and white to an image that has dark blue (RGB = 21, 41,66) where the original one had black. I know that GIMP probably has a feature that enables you to do just that, but I couldn’t find it. So I ended up writing my own little program using Processing that did exactly what I needed it to do. Here is the new header:

Final site header
Final site header

… and here is the Processing sketch I wrote to get the final header image:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
PImage myImage;
int myRed;
int myGreen;
int myBlue;
color myColor;
 
void setup(){
 
  size(607,110);
  background(255);
  myImage = loadImage("header.gif");
 
  for(int x=0; x<width+1; x++){
    for(int y =0; y<height+1; y++){
      color imgPixel = myImage.get(x,y);
 
      myRed = int(map(red(imgPixel),0,255,21,0));
      myGreen = int(map(green(imgPixel),0,255,41,0));
      myBlue = int(map(blue(imgPixel),0,255,66,0));  
      myColor = color(myRed, myGreen, myBlue);
      stroke(myColor);
      point(x,y);
    }
  }
}
 
void draw(){
  saveFrame("header.png"); 
  exit();
}

This little program does the following:

1. Opens the header.gif (which I have already saved in the data folder)

2. It reads every single pixel (using one loop for the x axis and one for the y axis)

3. Using the map() function three times, it creates a shade of blue based on the inverse shade of gray the original pixel had; it then draws a pixel using the new shade of blue.

4. When it has gone through all the pixels, it saves the image as header.png (in the sketch’s main directory) and exits.

Simple, yet so effective…