ActiveState Code

Recipe 527747: Invert CSS Hex colors


Simple program that takes a CSS file and inverts all the colors,(e.g.: #ffffff -> #000000, #222 -> #ddd), then writes them to a file with the same name as the original plus "MOD".

Python
 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
import re
import Tkinter, tkFileDialog
root = Tkinter.Tk()
root.withdraw()

p6 = re.compile("#[0-9a-f]{6};", re.IGNORECASE)
p3 = re.compile("#[0-9a-f]{3};", re.IGNORECASE)
filepath = tkFileDialog.askopenfilename(title= "file?",)
content = file(filepath,'r').read()

def Modify (content):
    text = content.group().lower()
    code = {}
    l1="#;0123456789abcdef"
    l2="#;fedcba9876543210"
    for i in range(len(l1)):
        code[l1[i]]=l2[i]
    inverted = ""
    for j in text:
        inverted += code[j]
    return inverted

content = p6.sub(Modify,content)
content = p3.sub(Modify,content)

filepath = filepath[:-4]+"MOD.css"
out = file(filepath,'w')
out.write(content)
out.close()

Discussion

This was actually a real-world requirement. The "Modify" function could easily be changed to add more red, darken, etc.

Comments

  1. 1. At 10:52 p.m. on 29 aug 2007, greg p said:

    Good Idea. This is a good idea. I thought it would be good to have it online, thus it's now a web utility:

    http://www.utilitymill.com/utility/Invert_Hex_Colors

    I simplified the code a bit too:

    table = string.maketrans(
        '0123456789abcdef',
        'fedcba9876543210')
    
    print hex_to_convert.lower().translate(table).upper()
    
  2. 2. At 7:36 p.m. on 30 oct 2007, rodrigo culagovski (the author) said:
    "I simplified the code a bit."
    

    Nice use of understatement, there.

Sign in to comment