What you are looking for is called a flood fill algorithm. Which basically will take the color of the pixel you clicked on as a seed. It will check for all the pixels that are connected to the seed pixel that have the same color of the seed and fill them to a desired color. There are two types of this algorithm: 8-directional and 4-directional. Where the neighbours are defined as such ( S = Seed, X = Connected ):
4-directional
----------------
| | X | |
----------------
| X | S | X |
----------------
| | X | |
----------------
8-directional
----------------
| X | X | X |
----------------
| X | S | X |
----------------
| X | X | X |
----------------
The recursive algorithm is like so (From Wikipedia):
Flood-fill (node, target-color, replacement-color):
1. If target-color is equal to replacement-color, return.
2. If the color of node is not equal to target-color, return.
3. Set the color of node to replacement-color.
4. Perform Flood-fill (one step to the west of node, target-color, replacement-color).
Perform Flood-fill (one step to the east of node, target-color, replacement-color).
Perform Flood-fill (one step to the north of node, target-color, replacement-color).
Perform Flood-fill (one step to the south of node, target-color, replacement-color).
5. Return.