Turning binary string into an image with PIL

You could use img.putdata:

import Image

value = "0110100001100101011011000110110001101111"

cmap = {'0': (255,255,255),
        '1': (0,0,0)}

data = [cmap[letter] for letter in value]
img = Image.new('RGB', (8, len(value)//8), "white")
img.putdata(data)
img.show()        

enter image description here


If you have NumPy, you could instead use Image.fromarray:

import Image
import numpy as np

value = "0110100001100101011011000110110001101111"

carr = np.array([(255,255,255), (0,0,0)], dtype='uint8')
data = carr[np.array(map(int, list(value)))].reshape(-1, 8, 3)
img = Image.fromarray(data, 'RGB')
img.save('/tmp/out.png', 'PNG')

but this timeit test suggests using putdata is faster:

value = "0110100001100101011011000110110001101111"*10**5

def using_fromarray():
    carr = np.array([(255,255,255), (0,0,0)], dtype='uint8')
    data = carr[np.array(map(int, list(value)))].reshape(-1, 8, 3)
    img = Image.fromarray(data, 'RGB')
    return img

def using_putdata():
    cmap = {'0': (255,255,255),
            '1': (0,0,0)}

    data = [cmap[letter] for letter in value]
    img = Image.new('RGB', (8, len(value)//8), "white")
    img.putdata(data)
    return img

In [79]: %timeit using_fromarray()
1 loops, best of 3: 1.67 s per loop

In [80]: %timeit using_putdata()
1 loops, best of 3: 632 ms per loop