Python: How to add text to code128 using Pillow.
Module code128 create barcode but without text
import code128
barcode_param = 'Hello World'
barcode_text = 'Hello World'
barcode_image = code128.image(barcode_param, height=100)
but it gives it as Pillow image so you can use Pillow to add margin for text and to draw this text.
You can get original size of barcode
w, h = barcode_image.size
Calculate new size with margins (top, bottom) for text
new_w = w # the same
margin = 20
new_h = h + (2*margin)
Create empty image new size and with white background
new_image = Image.new('RGB', (new_w, new_h), (255, 255, 255))
Put original barcode with top margin (to get in the middle of height)
new_image.paste(barcode_image, (0, margin))
Next you can use ImageDraw to create object to draw lines or put text on image
draw = ImageDraw.Draw(new_image)
And you can use text() to put black text using default font and font size
draw.text( (10, new_h - 10), barcode_text, fill=(0, 0, 0))
To change size you need to use ImageFont to load font and set size
fnt = ImageFont.truetype("arial.ttf", 40)
draw.text( (10, new_h - 10), barcode_text, fill=(0, 0, 0), font=fnt)
And you have image with text in new_image which you can save in file and display in browser
# save in file
new_image.save('barcode_image.png', 'PNG')
# show in default viewer
webbrowser.open('barcode_image.png')
or you can convert to bytes and send by internet
barcode_bytes = io.BytesIO()
new_image.save(barcode_bytes, "PNG")
barcode_bytes.seek(0)
data = barcode_bytes.getvalue()
In example I use standard module webbrowser only to check image.
import code128 from PIL import Image, ImageDraw, ImageFont import webbrowser # only to display it import io # only to send by network without saving on disk barcode_param = 'Hello World' barcode_text = 'Hello World' # original image barcode_image = code128.image(barcode_param, height=100) # empty image for code and text - it needs margins for text w, h = barcode_image.size margin = 20 new_w = w new_h = h + (2*margin) # margin top and bottom # empty image with white border and new size new_image = Image.new('RGB', (new_w, new_h), (255, 255, 255)) # put barcode on new image - with top margin new_image.paste(barcode_image, (0, margin)) # object to draw text draw = ImageDraw.Draw(new_image) # draw text #fnt = ImageFont.truetype("arial.ttf", 40) draw.text( (10, new_h-10), barcode_text, fill=(0, 0, 0))#, font=fnt) # # save in file new_image.save('barcode_image.png', 'PNG') # show in default viewer webbrowser.open('barcode_image.png') new_image.show() # --- later send it --- barcode_bytes = io.BytesIO() new_image.save(barcode_bytes, "PNG") barcode_bytes.seek(0) data = barcode_bytes.getvalue()
Notes:
Stackoverflow: How to include barcode value with actual barcode Python code128 module
Buy a Coffee