python生成二维码

python生成二维码

需要用到的包

pip install qrcode 

代码:

import qrcode

from PIL import Image # 如果需要在二维码中添加图片logo需要

# 模块导入

data = "www.baidu.com"
img_name = '二维码.png'  # 图片名称

# 实例化QRcode生成qr对象
qr = qrcode.QRCode(
    # 表示二维码的大小 范围1-40 如果想让程序自动生成,将值设置为 None 并使用 fit=True 参数即可。
    version=1,
    # 二维码的纠错范围 1. ERROR_CORRECT_L 7%以下的错误会被纠正2. ERROR_CORRECT_M (default) 15%以下的错误会被纠正3. ERROR_CORRECT_Q 25 %以下的错误会被纠正4. ERROR_CORRECT_H. 30%以下的错误会被纠正
    error_correction=qrcode.constants.ERROR_CORRECT_H,
    # 每个点(方块)中的像素个数
    box_size=10,
    # 边框 最小为4
    border=4
)

# 传入数据
qr.add_data(data)

qr.make(fit=True)

# 生成二维码
img = qr.make_image()
img = img.convert("RGBA")

'''
这段为添加图片logo代码 start
'''
# 添加logo,打开logo照片
icon = Image.open("logo.png")
# 获取图片的宽高
img_w, img_h = img.size
# 参数设置logo的大小
factor = 4
size_w = int(img_w / factor)
size_h = int(img_h / factor)
icon_w, icon_h = icon.size
if icon_w > size_w:
    icon_w = size_w
if icon_h > size_h:
    icon_h = size_h

# 重新设置logo的尺寸
icon = icon.resize((icon_w, icon_h), Image.ANTIALIAS)

# 得到画图的x,y坐标,居中显示
w = int((img_w - icon_w) / 2)
h = int((img_h - icon_h) / 2)
icon = icon.convert("RGBA")

# 黏贴logo照
img.paste(icon, (w, h), icon)
'''
这段为添加图片logo代码 end
'''
img.save(img_name)
img.show()

  • 4
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值