1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
| import qrcode from PIL import Image, ImageDraw, ImageFont import os
# 输入库位编码和名称 qr_text = input("输入库位编码:") qr_name = input("输入库位名称:")
# 检查输入是否为空 if not qr_text or not qr_name: print("库位编码和名称不能为空!") exit()
# 生成二维码 qr = qrcode.QRCode( version=1, error_correction=qrcode.constants.ERROR_CORRECT_L, box_size=30, border=4, ) qr.add_data(qr_text) qr.make(fit=True)
img = qr.make_image(fill='black', back_color='white')
# 加载字体(使用系统默认字体或指定字体路径) try: font_path = "arial.ttf" # 可以替换为字体文件的完整路径 font = ImageFont.truetype(font_path, 80) except IOError: print("字体文件未找到,使用默认字体。") font = ImageFont.load_default()
# 创建可以在图片上绘图的对象 draw = ImageDraw.Draw(img)
# 计算文本位置(居中) # 使用 getbbox 获取文本的边界框 text_bbox = font.getbbox(qr_name) text_width = text_bbox[2] - text_bbox[0] # 右边界 - 左边界 text_height = text_bbox[3] - text_bbox[1] # 下边界 - 上边界
img_width, img_height = img.size text_x = (img_width - text_width) // 2 text_y = 20 # 距离顶部的距离
# 绘制文本 draw.text((text_x, text_y), qr_name, font=font, fill='black')
# 保存图片 output_filename = f"{qr_name}.png" img.save(output_filename) print(f"二维码已保存为 {output_filename}")
|