How To Generate Barcode In Python

This article shows a demo of how to generate barcodes as well as how to generate them in png format.

First, let’s create a simple barcode using the pyplot module.

To prevent interpolation artifacts figure size is calculated so that the width in the pixel is multiple of the number of data points.

#Code for Barcode generation
import matplotlib.pyplot as plt
import numpy as np


code = np.array([
    1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 1, 1,
    0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0,
    1, 0, 1, 0, 0, 0, 0, 1, 0, 1, 1, 1, 0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1,
    1, 0, 0, 1, 1, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1])

pixel_per_bar = 6
dpi = 200

fig = plt.figure(figsize=(len(code) * pixel_per_bar / dpi, 1), dpi=dpi)
ax = fig.add_axes([0, 0, 1, 1])  # span the whole figure
ax.set_axis_off()
ax.imshow(code.reshape(1, -1), cmap='binary', aspect='auto',
          interpolation='nearest')
plt.show()

Output :

You can also change the way the barcode looks by modifying its dpi, pixel_per_bar, and the second parameter of the figure.

Now let’s try to create another one using the module python-barcode.

Modules Needed : 

python-barcode:

#install python-barcode module
pip install python-barcode

Pillow: Used to create barcode in image format

#install pillow module
pip install pillow

1. Generating in SVG format.

# barcode generator
from barcode import EAN13

# pass the number as string
number = '5678998765456'
# Now create an object of EAN13
my_code = EAN13(number)
my_code.save("new_code")

For PNG format use image writer.

# barcode generator
from barcode import EAN13
#  ImageWriter to generate an image file
from barcode.writer import ImageWriter

#pass the number as string
number = '5678998765456'
my_code = EAN13(number, writer=ImageWriter())
my_code.save("new_code1")

Hope It is useful to you. For suggestions leave a comment.

Thanks for read.

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories