Created
March 12, 2014 20:47
-
-
Save sfan5/9515942 to your computer and use it in GitHub Desktop.
Generates an image with an EAN-8 barcode
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
from PIL import Image | |
import sys | |
l_code = { | |
0: '0001101', | |
1: '0011001', | |
2: '0010011', | |
3: '0111101', | |
4: '0100011', | |
5: '0110001', | |
6: '0101111', | |
7: '0111011', | |
8: '0110111', | |
9: '0001011', | |
} | |
r_code = { | |
0: '1110010', | |
1: '1100110', | |
2: '1101100', | |
3: '1000010', | |
4: '1011100', | |
5: '1001110', | |
6: '1010000', | |
7: '1000100', | |
8: '1001000', | |
9: '1110100', | |
} | |
colors = [(255, 255, 255), (0, 0, 0)] | |
height = 150 | |
sepheight = 175 | |
width = 5 | |
marginx = 50 | |
marginy = 50 | |
def draw_bars(pxl, bx, by, wd, hh, cols, stv): | |
x = bx | |
for e in stv: | |
col = cols[1 if e == '1' else 0] | |
for xx in range(x, x + wd): | |
for y in range(by, by + hh): | |
pxl[xx, y] = col | |
x += wd | |
return x - bx | |
if len(sys.argv) <= 2: | |
print('Usage: %s <ean8> <output>' % sys.argv[0]) | |
else: | |
code = sys.argv[1] | |
if len(code) != 8: | |
print('Not an EAN-8') | |
exit(1) | |
img = Image.new('RGB', ((3+(7*4)+5+(7*4)+3) * width + (marginx*2), sepheight + (marginy*2)), colors[0]) | |
imgd = img.load() | |
x = marginx | |
x += draw_bars(imgd, x, marginy, width, sepheight, colors, '101') # First seperator | |
f4code = ''.join(l_code[int(e)] for e in code[:4]) | |
x += draw_bars(imgd, x, marginy, width, height, colors, f4code) # First four numbers | |
x += draw_bars(imgd, x, marginy, width, sepheight, colors, '01010') # Middle seperator | |
l4code = ''.join(r_code[int(e)] for e in code[4:]) | |
x += draw_bars(imgd, x, marginy, width, height, colors, l4code) # Last four numbers | |
x += draw_bars(imgd, x, marginy, width, sepheight, colors, '101') # Last seperator | |
img.save(sys.argv[2]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment