f = open(outfn, 'wb')
f.write(struct.pack('HH', H, W))
for j in range(H):
for i in range(0, W, 8):
byte = 0
for bit_i in range(8):
try:
bit = im.getpixel((i + bit_i, j)) < 255
except:
bit = False
# sys.stdout.write(' X'[bit])
byte |= bit << bit_i
f.write(struct.pack('B', byte))
print 'wrote', outfn