Skip to content

Instantly share code, notes, and snippets.

@orangepeelbeef
Last active January 4, 2020 19:23
Show Gist options
  • Save orangepeelbeef/e6c9ebdbcc9ee33c2ed3f97e24ec9647 to your computer and use it in GitHub Desktop.
Save orangepeelbeef/e6c9ebdbcc9ee33c2ed3f97e24ec9647 to your computer and use it in GitHub Desktop.
decode an ascii qrencode to an image
# take an ascii qrcode from qrencode and make it a png
from PIL import Image
import re
import sys
try:
with open(sys.argv[1]) as fp:
line = fp.readline().strip('\n')
# get columns count dynamically from file
# file must have same length in every line
cols = len(line)
# we expect the white value to be a space
zero_char = r'[ ]'
# we expect the black value to be a hash
one_char = r'[#]'
# handle the first line we read above so we don't drop it in case the file is not padded
line = re.sub(zero_char, '0', line)
line = re.sub(one_char, '1', line)
bitstring = line + line
while line:
line = fp.readline().strip('\n')
# replace zeros and ones
line = re.sub(zero_char, '0', line)
line = re.sub(one_char, '1', line)
# ascii version has to double stack the rows since there are half as many rows as columns
bitstring += line + line
# print bitstring out for debugging
print(bitstring)
# make square image the size of line length
# make it a white image, so we only need to write black characters where there are 1's
outimg = Image.new("RGB", (cols, cols), "white")
pixels_out = outimg.load()
# determine number of rows
rows = int(len(bitstring)/cols)
count = -1
# write out the png row by row
for r in range(0, rows):
for c in range(0, cols):
count += 1
if bitstring[count] == "1":
pixels_out[(c, r)] = (0, 0, 0)
outimg.save("qrout.png", "png")
except:
print("Run as {} location/to/qrfile.txt\nMake sure file exists and all lines of file are of same length".format(sys.argv[0]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment