Created
June 4, 2015 17:30
-
-
Save ntrrgc/39a6147b90d1bfdeb40e to your computer and use it in GitHub Desktop.
Convert colon separated hex color strings into palette images and vice versa
This file contains hidden or 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
#!/usr/bin/python | |
import sys | |
from PIL import Image, ImageDraw, ImageColor | |
from argparse import ArgumentParser | |
cell_w = cell_h = 40 | |
def color_to_hex(color): | |
return '#' + ''.join('%02x' % x for x in color) | |
def to_image(input_file, output_file, delim): | |
if input_file == '-': | |
input_file = sys.stdin | |
else: | |
input_file = open(input_file, 'r') | |
if output_file == '-': | |
output_file = open(sys.stdout, 'wb') | |
else: | |
output_file = open(output_file, 'wb') | |
hex_codes = input_file.read().strip().split(delim) | |
img = Image.new('RGB', (cell_w * len(hex_codes), cell_h)) | |
draw = ImageDraw.Draw(img) | |
for i, color_code in enumerate(hex_codes): | |
color = ImageColor.getrgb(color_code) | |
draw.rectangle(((cell_w * i, 0), | |
(cell_w * (i + 1), cell_h)), | |
color) | |
img.save(output_file, "PNG") | |
def from_image(input_file, output_file, delim): | |
if input_file == '-': | |
input_file = sys.stdin.dettach() | |
else: | |
input_file = open(input_file, 'rb') | |
if output_file == '-': | |
output_file = open(sys.stdout, 'w') | |
else: | |
output_file = open(output_file, 'w') | |
img = Image.open(input_file) | |
num_colors = img.size[0] // cell_w | |
hex_codes = [] | |
for i in range(num_colors): | |
color = img.getpixel((i * cell_w, 0)) | |
hex_codes.append(color_to_hex(color)) | |
output_file.write(delim.join(hex_codes) + '\n') | |
output_file.close() | |
if __name__ == "__main__": | |
parser = ArgumentParser(description= | |
"Converts a list of hex colors into an image and vice versa.") | |
group_action = parser.add_mutually_exclusive_group(required=True) | |
group_action.add_argument("--to-image", dest="to_image", action="store_true") | |
group_action.add_argument("--from-image", dest="from_image", action="store_true") | |
parser.add_argument("-d", dest="delimiter", default=":", type=str) | |
parser.add_argument("input_file", type=str) | |
parser.add_argument("output_file", type=str) | |
args = parser.parse_args() | |
if args.to_image: | |
to_image(args.input_file, args.output_file, args.delimiter) | |
else: | |
from_image(args.input_file, args.output_file, args.delimiter) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment