Conversion experiment 2: Difference between revisions
(Created page with "Text to image conversion experiment. <br /> <source lang="python"> import binascii from PIL import Image import math data = open('example_1.txt') txt = data.read() color = []...") |
No edit summary |
||
Line 11: | Line 11: | ||
def text_to_bits(text, encoding='utf-8', errors='surrogatepass'): | def text_to_bits(text, encoding='utf-8', errors='surrogatepass'): | ||
bits = bin(int(binascii.hexlify(text.encode(encoding, errors)), 16))[2:] | |||
return bits.zfill(8 * ((len(bits) + 7) // 8)) | |||
values = text_to_bits(txt) | values = text_to_bits(txt) | ||
values_div = [values[i:i+8] for i in range(0, len(values), 8)] | values_div = [values[i:i+8] for i in range(0, len(values), 8)] | ||
Line 20: | Line 20: | ||
def group(lst, n): | def group(lst, n): | ||
for i in range(0, len(lst), n): | |||
val = lst[i:i+n] | |||
if len(val) == n: | |||
yield tuple(val) | |||
RGB = list(group(color, 3)) | RGB = list(group(color, 3)) | ||
print RGB | print RGB |
Revision as of 20:09, 5 December 2015
Text to image conversion experiment.
import binascii
from PIL import Image
import math
data = open('example_1.txt')
txt = data.read()
color = []
n = 0
def text_to_bits(text, encoding='utf-8', errors='surrogatepass'):
bits = bin(int(binascii.hexlify(text.encode(encoding, errors)), 16))[2:]
return bits.zfill(8 * ((len(bits) + 7) // 8))
values = text_to_bits(txt)
values_div = [values[i:i+8] for i in range(0, len(values), 8)]
for value in values_div:
value = int(value,2)
color.append(value)
def group(lst, n):
for i in range(0, len(lst), n):
val = lst[i:i+n]
if len(val) == n:
yield tuple(val)
RGB = list(group(color, 3))
print RGB
print len(RGB)
x = int(math.sqrt(len(RGB)))
img = Image.new('RGB',(x, x), "white")
pix=img.load()
w=img.size[0]
h=img.size[1]
for i in range(w):
for j in range(h):
r = RGB[n][0]
g = RGB[n][1]
b = RGB[n][2]
img.putpixel((i,j),(r,g,b))
n = n+1
img.show()