Last active
October 17, 2024 16:03
-
-
Save Chaz6/25114660c712ea0ed3a72541a8201daa to your computer and use it in GitHub Desktop.
Generate an svg data matrix barcode for a uuid
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 python3 | |
import uuid as _uuid | |
import argparse | |
from itertools import batched | |
from pylibdmtx.pylibdmtx import encode | |
size = 18 | |
size_with_margin = size + 4 | |
encoding = "Base256" | |
def generate_barcode(quantity: int): | |
uuid = _uuid.uuid4() | |
dmtx = encode(uuid.bytes, encoding, f"{size}x{size}") | |
h = dmtx.height | |
w = dmtx.width | |
bpp = int(dmtx.bpp / 8) | |
repeat = int(h / size_with_margin) | |
output_w = w / repeat | |
output_h = h / repeat | |
data = f"""<svg width="{output_w}" height="{output_h}" xmlns="http://www.w3.org/2000/svg">""" | |
p_y = -1 | |
for row in batched(dmtx.pixels, w * bpp * repeat): | |
p_x = -1 | |
p_y += 1 | |
for column in batched(row[: w * bpp], bpp * repeat): | |
p_x += 1 | |
if not column[0]: | |
data += f"""<rect width="1" height="1" x="{p_x}" y="{p_y}" style="fill:black; />""" | |
data += "</svg>" | |
# Write the SVG to a file | |
output_file_name = f"datamatrix_{encoding.lower()}_{w}x{h}_{uuid.hex}" | |
with open(f"{output_file_name}.svg", "w") as f: | |
f.write(data) | |
if __name__ == "__main__": | |
parser = argparse.ArgumentParser() | |
parser.add_argument( | |
"quantity", | |
type=int, | |
help="Number of barcodes to generate", | |
nargs="?", | |
default=1, | |
) | |
args = parser.parse_args() | |
for i in range(args.quantity): | |
generate_barcode(i) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment