Conversion experiment 2
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.save('text_to_image.png')
img.show()