图书室每隔一段时间就要办理一批借书卡,原有借阅系统软件只能批量生成所有用户的借书卡或者单个借书卡,每次生成一大堆卡片,太麻烦了,思路为增加用户账号,手动生成借书卡并打印塑封。
自带的借书卡图片如下:
思路:
- 读取会员记录文本文件;从excel中复制过来的
- 按照会员账号生成条形码
- 准备背景图片
- 将会员姓名和条形码写到背景图片上,
- 按照姓名和账号保存成新的图片
import barcode
from barcode.writer import ImageWriter
from PIL import Image, ImageDraw, ImageFont
f = open("text.txt","r")
ls = []
f = f.readlines()
for line in f:
line = line.strip('\n')
line = line.split('\t')
ls.append(line)
print(ls)
for li in ls:
# barcode模块能自动计算验证码
code1 = barcode.generate('code128',li[2],
writer=barcode.writer.ImageWriter(),
output=li[0] + li[1] + li[2],
writer_options={"background": "white","module_width": 0.15,"module_height":3.0,"font_size":4,"text_distance":2.0,},
text= li[2])
# 简:写:
# code2 = barcode.generate('ean13','2312123123132',barcode.writer.ImageWriter(),'barcode_png2',{"background": "red"},text='weerwr')
#图像拼叠
background_image = 'bg.jpg'
foreground_image = li[0] + li[1] + li[2] + '.png'
background = Image.open(background_image)
foreground = Image.open(foreground_image)
position = (20, 220) # 前景图片粘贴位置
background.paste(foreground, position)
background.save(foreground_image)
#写入文字姓名
img = Image.open(li[0] + li[1] + li[2] + '.png')
draw = ImageDraw.Draw(img)
#text1
text = li[1]
font = ImageFont.truetype("msyh.ttf", 36)
fill_color = (0, 0, 0)
text_x,text_y = 120,70
draw.text((text_x, text_y), text, fill=fill_color, font=font)
#text2
text = li[0]
text_x,text_y = 10,10
font = ImageFont.truetype("msyh.ttf", 10)
draw.text((text_x, text_y), text, fill=fill_color, font=font)
img.save(li[0] + li[1] + li[2] + '.png')
print("条形码图片保存完成")
生成的借书卡如图: