Today, I’m excited to share with you how I created a Barcode Generator using Python. Barcodes are widely used for product labeling, inventory management, and even ticketing systems. With just a few lines of code and the python-barcode
library, you can generate your own barcodes dynamically.
I’ll explain the code step by step, add some extra functionality, and demonstrate how to make it practical for real-world applications. By the end, you’ll have a fully functional and flexible barcode generator!
Install the Required Libraries
First things firstmbefore writing any code, make sure you have the required libraries installed.
pip install python-barcode
pip install pillow
python-barcode
: This library is used to generate barcodes.pillow
: A popular library for working with image files, which we’ll use for saving barcodes as PNG images.
Import Necessary Libraries
Here’s the initial setup for our project:
import barcode
from barcode.writer import ImageWriter
from IPython.display import Image, display
barcode
: The core library that helps us generate barcodes.ImageWriter
: Used to save the generated barcode as an image (e.g., PNG).Image, display
: For displaying the barcode image in an interactive environment like Jupyter Notebook.
Define the Barcode Format and Number
Next, we define the barcode format (EAN13
) and the number to encode:
Barcode_format = barcode.get_barcode_class('ean13')
barcode_number = '1234567895540'
barcode.get_barcode_class('ean13')
: This selects the EAN13 barcode format, which is widely used for product labeling.barcode_number
: The input number to encode in the barcode. For EAN13, you need a 12-digit number, and the library automatically calculates the 13th digit (the check digit).
Create the Barcode Image
Now, we use the defined format and number to create a barcode image:
barcode_image = barcode_format(barcode_number, writer=ImageWriter())
writer=ImageWriter()
: This specifies that the output should be saved as an image (PNG format).
Save the Barcode Image
To make the barcode reusable, we save it to a file:
barcode_filename = 'barcode_image'
barcode_image.save(barcode_filename)
This saves the barcode as barcode_image.png
in the current directory.
Display the Barcode Image
For a quick visual confirmation, you can display the barcode image in an interactive Python environment:
Display(Image(filename=f'{barcode_filename}.png'))
This will render the barcode directly in Jupyter Notebook or any other interactive environment.
Adding More Practical Functionality
To make the barcode generator more flexible, I added several practical features:
- Dynamic user input for barcode numbers.
- Validation to ensure the number meets the EAN13 format.
- Support for multiple barcode formats (EAN13, Code128, UPC, etc.).
- Custom filenames for saved barcodes.
- Error handling for invalid inputs or other issues.
The Enhanced Barcode Generator Code
Here’s the upgraded version of the barcode generator:
import barcode
from barcode.writer import ImageWriter
from IPython.display import Image, display
def generate_barcode(barcode_number, format='ean13', filename='barcode_image'):
"""
Generates and saves a barcode image.
Parameters:
barcode_number (str): The number to encode in the barcode.
format (str): The barcode format (default is 'ean13').
filename (str): The filename to save the barcode image.
Returns:
str: Path to the saved barcode image.
"""
try:
# Get the barcode class based on the format
barcode_format = barcode.get_barcode_class(format)
# Validate the barcode number (EAN13 requires 12 digits)
if format == 'ean13' and len(barcode_number) != 12:
raise ValueError("EAN13 format requires a 12-digit number.")
# Create the barcode image
barcode_image = barcode_format(barcode_number, writer=ImageWriter())
# Save the barcode image to a file
filepath = f'{filename}.png'
barcode_image.save(filename)
print(f"Barcode saved as: {filepath}")
# Display the barcode image (for Jupyter Notebooks)
display(Image(filename=filepath))
return filepath
except Exception as e:
print(f"Error: {e}")
# Example usage
if __name__ == "__main__":
# Prompt the user for a barcode number
barcode_number = input("Enter a 12-digit number for the EAN13 barcode: ")
# Generate and save the barcode
generate_barcode(barcode_number, format='ean13', filename='custom_barcode')
Features of the Enhanced Code
Dynamic User Input:
barcode_number = input("Enter a 12-digit number for the EAN13 barcode: ")
Prompts the user to enter a barcode number. This allows generating custom barcodes without modifying the script.
Validation:
if format == 'ean13' and len(barcode_number) != 12:
raise ValueError("EAN13 format requires a 12-digit number.")
Ensures that the number is valid for the chosen format. For example, EAN13 requires exactly 12 digits.
Support for Multiple Barcode Formats:
format='ean13'
You can change the format to code128
, upc
, or others supported by the python-barcode
library.
Custom Filename:
filename='custom_barcode'
Allows you to specify a custom name for the saved file.
Error Handling:
except Exception as e:
print(f"Error: {e}")
Gracefully handles errors, such as invalid inputs, and provides meaningful feedback to the user.
How to Use the Enhanced Code
- Run the script in any Python environment (e.g., terminal, IDE, or Jupyter Notebook).
- Enter a valid 12-digit number when prompted (e.g.,
123456789012
). - The script will:
- Validate the input number.
- Generate an
EAN13
barcode. - Save the barcode as an image file (e.g.,
custom_barcode.png
). - Display the barcode if running in an interactive environment.
Final Output
Once you run the script, you’ll see:
- A barcode image saved to the specified file (e.g.,
custom_barcode.png
). - The barcode displayed directly in your Python environment (if using Jupyter Notebook).
Conclusion
Creating a barcode generator with Python is both simple and powerful. This project can be easily adapted for real-world applications like inventory management, product labeling, or even ticket generation. With the enhancements added, the code is now flexible, user-friendly, and suitable for various use cases.