Skip to content

Instantly share code, notes, and snippets.

@rweir
Forked from danostrowski/change_color.py
Last active August 29, 2015 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rweir/536585d4bbb85ff5cfce to your computer and use it in GitHub Desktop.
Save rweir/536585d4bbb85ff5cfce to your computer and use it in GitHub Desktop.
def color_change1(original, new_color):
"""
Change a color in a single-color transparent PNG.
@type im: PIL.Image
@type new_color: tuple
"""
# get the data for the image as a sequence of tuples
# carve out memory for the converted image data
converted = []
# instead of making a new tuple for the same data,
# index by alpha channel with a tuple for the color
tups = {}
for pixel in original.getdata():
alpha = pixel[3]
if alpha not in tups:
# record a tuple for this alpha level
tups[alpha] = new_color + (alpha,)
# add color to new image data
converted.append(tups[alpha])
im2 = Image.new(original.mode, original.size)
im2.putdata(converted)
return im2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment