As I said in a comment under @pedrosorio's answer, I think this could be done more efficently by using table lookups. This means virtually all of the mathematical calculations are done once, when the table is created, and is only done 256 times, rather for each and every pixel. Here's what I mean, using pedrosorio's formula:
tbl = tuple(51*((int(i)+25)//51) for i in xrange(256))
def websafe(*color):
return tuple(tbl[c] for c in color)
safecolor = websafe(34,55,13)
However, I'm not sure about how the formula maps the 0-255 range values -- because it assigns the following number of entries for each of the six primary shades:
shade count
0x00 26
0x33 51
0x66 51
0x99 51
0xcc 51
0xff 26
Instead, I would use this slightly simpler formula:
tbl = tuple(51*(i//43) for i in xrange(256))
which gives a more even distribution of the shades:
shade count
0x00 43
0x33 43
0x66 43
0x99 43
0xcc 43
0xff 41
Once you know the distribution count you could even do something like this which involves very little math. Of course there's little reason to bother optimizing non-speed-crucial code.
tbl = ((0x00,)*43 + (0x33,)*43 + (0x66,)*43 +
(0x99,)*43 + (0xcc,)*43 + (0xff,)*41)