Created
July 17, 2011 21:49
-
-
Save benosteen/1088117 to your computer and use it in GitHub Desktop.
Visual hash of a hex number (UUID for eg)
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 | |
def value_to_trinary(value): | |
trin = "" | |
orig = value | |
while(value): | |
mod = value % 3 | |
value = value / 3 | |
trin = str(mod) + trin | |
while(len(trin) < 3): | |
trin = "0" + trin | |
return trin | |
def to_row(value, width=6, COLOURS=("\x16\x32\xff", "\xff\x16\x00", "\x45\xff\x00")): | |
data = "" | |
if value == 0: | |
return COLOURS[0]*width*3 | |
else: | |
trin = value_to_trinary(value) | |
for digit in trin: | |
data = data + (COLOURS[int(digit)] * width) | |
return data | |
def hex_to_bar(hex_string, width=6): | |
data = "" | |
for hd in hex_string: | |
val = int(hd, 16) | |
data = data + to_row(val, width=width) | |
return data | |
def hex_to_image(hex_string, width=6): | |
data = hex_to_bar(hex_string) | |
i = Image.fromstring("RGB", (width*3, len(data)/(width*9)), data) | |
i = i.rotate(90) | |
return i | |
def get_sig_value(sig, SIG_COLOURS=("1","2","0")): | |
if sig[0] > sig[1]: | |
if sig[0] > sig[2]: | |
return SIG_COLOURS[0] | |
else: | |
return SIG_COLOURS[2] | |
elif sig[1] > sig[2]: | |
return SIG_COLOURS[1] | |
else: | |
return SIG_COLOURS[2] | |
def imagefile_to_hex(image_filename, SIG_COLOURS=("1","2","0")): | |
im = Image.open(image_filename) | |
return image_to_hex(im, SIG_COLOURS=SIG_COLOURS) | |
def image_to_hex(im, SIG_COLOURS=("1","2","0")): | |
im = im.rotate(-90) | |
width, height = im.size | |
step = width / 3 | |
offset = width / 6 | |
raw = list(im.getdata()) | |
cursor_h = 0 | |
hex_string = "" | |
while(cursor_h != height): | |
s = get_sig_value(raw[offset]) | |
s = s+get_sig_value(raw[offset+step]) | |
s = s+get_sig_value(raw[offset+(step*2)]) | |
hex_string = hex_string + hex(int(s,3))[-1] | |
cursor_h += 1 | |
raw = raw[width:] | |
return hex_string | |
def test(): | |
from uuid import uuid4 | |
u = uuid4().hex | |
print "Encoding %s to 'test.png'" % u | |
i = hex_to_image(u) | |
i.save("test.png", "PNG") | |
print "Attempting to load image and decode" | |
hex_str = imagefile_to_hex('test.png') | |
print "Got %s from file" % hex_str | |
hex_str2 = image_to_hex(i) | |
print "Got %s directly" % hex_str2 | |
print "Should be %s" % u | |
assert u == hex_str | |
assert u == hex_str2 | |
if __name__ == "__main__": | |
test() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment