Created
March 29, 2017 16:35
-
-
Save bolencki13/5b85ba73034cca4b5abe6f8508bbf993 to your computer and use it in GitHub Desktop.
Change the color of an image file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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