How To Include Barcode Value With Actual Barcode Python `code128` Module
Solution 1:
You get code as Pillow image so you can use Pillow to add margin for text and to draw this text.
You can get original size
w, h = barcode_image.size
calculate new size
new_w = w # the same
margin = 20
new_h = h + (2*margin)
create empty image with white background
new_image = Image.new('RGB', (new_w, new_h), (255, 255, 255))
put original barcode in the middle of height
new_image.paste(barcode_image, (0, margin))
Next you can use ImageDraw
to create object which can draw objects or put text on image
draw = ImageDraw.Draw(new_image)
and you can put some text using text()
. You may need to use ImageFont
to load font and set size. I use default font and 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
. And you can save it in file and check directly in web browser or you can convert to bytes and send to client.
In example I use standard module webbrowser
only to check image.
EDIT
As @RufusVS noted in comment I could use image_new.show()
instead of webbrowser
import code128
import io
from PIL import Image, ImageDraw, ImageFont
barcode_param = '1234'
barcode_text = 'theseahawksarewinning'
# 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_h = h +(2*margin)
new_image = Image.new( 'RGB', (w, new_h), (255, 255, 255))
# put barcode on new image
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
import webbrowser
webbrowser.open('barcode_image.png')
# --- later send it---
barcode_bytes = io.BytesIO()
new_image.save(barcode_bytes, "PNG")
barcode_bytes.seek(0)
data = barcode_bytes.getvalue()
Doc: Image Image.new(), ImageDraw, ImageDraw.text() ImageFont
Post a Comment for "How To Include Barcode Value With Actual Barcode Python `code128` Module"