Skip to content

Instantly share code, notes, and snippets.

@bolencki13
Created March 29, 2017 16:35
Show Gist options
  • Save bolencki13/5b85ba73034cca4b5abe6f8508bbf993 to your computer and use it in GitHub Desktop.
Save bolencki13/5b85ba73034cca4b5abe6f8508bbf993 to your computer and use it in GitHub Desktop.
Change the color of an image file
from PIL import Image
import sys
import os
picture = None
picturePath = None
def validateColor(hex):
return (len(hex) == 7)
def hexToRGB(hex):
value = hex.lstrip('#')
lv = len(value)
return tuple(int(value[i:i + lv // 3], 16) for i in range(0, lv, lv // 3))
def changeColor(oldColor, newColor):
width, height = picture.size
for x in range(width):
for y in range(height):
current_color = picture.getpixel((x,y))
if current_color[0] is oldColor[0] and current_color[1] is oldColor[1] and current_color[2] is oldColor[2] and current_color[3] is not 0:
picture.putpixel((x,y), (newColor[0],newColor[1],newColor[2]))
path = picturePath.replace(os.path.basename(picturePath),'')
picture.save(path + "new_" + os.path.basename(picturePath))
def help():
print("colorChange needs 3 arguments: file origColor changeColor\ncolors must be hex values")
if __name__ == "__main__":
if len(sys.argv) == 4:
picturePath = sys.argv[1]
picture = Image.open(picturePath)
if picture is not None:
origColor = None;
if validateColor(sys.argv[2]) is True:
origColor = hexToRGB(sys.argv[2])
newColor = None
if validateColor(sys.argv[3]) is True:
newColor = hexToRGB(sys.argv[3])
if origColor is not None and newColor is not None:
changeColor(origColor, newColor)
else:
print("Invalid color")
else:
help()
@bolencki13
Copy link
Author

Usage: python3 colorChange.py path/to/image.png "#ffffff" "#000000"

#ffffff -> original color to be changed
#000000 -> new value of color that was to be changed

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment