Created
March 2, 2016 11:38
-
-
Save alekseysidorov/1cbaef086315d50c8d19 to your computer and use it in GitHub Desktop.
Usage: make_barcodes.py --barcodes code1 code2 -o out.png
This file contains hidden or 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 | |
# -*- coding: utf-8 -*- | |
from PIL import Image | |
import requests | |
from io import BytesIO | |
import argparse | |
def make_barcode(barcode): | |
url = "http://barcode.tec-it.com/barcode.ashx?data={0}&code=Code128&dpi=96&download=true".format(barcode) | |
response = requests.get(url) | |
img = Image.open(BytesIO(response.content)) | |
print("Loaded img for {0}".format(barcode)) | |
return img | |
def make_barcodes(barcodes): | |
images = [] | |
for barcode in barcodes: | |
images += [make_barcode(barcode)] | |
return images | |
def compute_bounds(images, margins, spacing): | |
width, height = 0, 0 | |
for img in images: | |
width = max(width, img.size[0]) | |
height += img.size[1] + spacing | |
return (width + 2 * margins, height + 2 * margins) | |
def merge_images(images, margins, spacing): | |
bounds = compute_bounds(images, margins, spacing) | |
out = Image.new("RGB", bounds, color="white") | |
y = margins | |
for img in images: | |
out.paste(img, (margins, y)) | |
y += img.size[1] + spacing | |
return out | |
# client code | |
parser = argparse.ArgumentParser() | |
parser.add_argument('-c', '--barcodes', nargs='+', type=str) | |
parser.add_argument('-o', '--output', type=str, default="out.png") | |
args = parser.parse_args() | |
codes = args.barcodes | |
images = make_barcodes(codes) | |
out = merge_images(images, margins=10, spacing=5) | |
print("Writed output image into {0}".format(args.output)) | |
out.save(args.output) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment