如何在Python中生成条形码?
在本文中,我们将编写一个简短的脚本来使用Python生成条形码。我们将使用python-barcode模块,它是pyBarcode模块的一个分支。该模块为我们提供了以 SVG 格式生成条形码的功能。 Pillow需要生成图像格式(例如 png 或 jpg)的条形码。
需要的模块
- python-barcode:此模块用于将条形码创建为 SVG 对象。它使我们能够创建不同标准类型的条码,例如 EAN-8、EAN-13、EAN-14、UPC-A、JAN、ISBN-10、ISBN-13 等等。要安装此模块,请在终端中键入以下命令。
pip install python-barcode
- Pillow:用于创建图像格式的条形码。要安装此模块,请在终端中键入以下命令。
pip install pillow
在这里,我们将生成 EAN-13 格式的条形码。首先,让我们将其生成为 SVG 文件。
Python3
# import EAN13 from barcode module
from barcode import EAN13
# Make sure to pass the number as string
number = '5901234123457'
# Now, let's create an object of EAN13
# class and pass the number
my_code = EAN13(number)
# Our barcode is ready. Let's save it.
my_code.save("new_code")
Python3
# import EAN13 from barcode module
from barcode import EAN13
# import ImageWriter to generate an image file
from barcode.writer import ImageWriter
# Make sure to pass the number as string
number = '5901234123457'
# Now, let's create an object of EAN13 class and
# pass the number with the ImageWriter() as the
# writer
my_code = EAN13(number, writer=ImageWriter())
# Our barcode is ready. Let's save it.
my_code.save("new_code1")
输出:
现在,让我们以 PNG 格式生成相同的条形码。
Python3
# import EAN13 from barcode module
from barcode import EAN13
# import ImageWriter to generate an image file
from barcode.writer import ImageWriter
# Make sure to pass the number as string
number = '5901234123457'
# Now, let's create an object of EAN13 class and
# pass the number with the ImageWriter() as the
# writer
my_code = EAN13(number, writer=ImageWriter())
# Our barcode is ready. Let's save it.
my_code.save("new_code1")
输出: