Python 生成带Logo的圆角二维码

Python 生成二维码方式就不累述了,不会的自己百度吧

但python生成的二维码太难看了,要么没有logo,要么logo直接贴进去的,难看死了,有的也处理了一下,但没有圆角,也难看:

以下:是不是觉得最后一个好看!!!

直接上代码:

import qrcode
from PIL import Image, ImageDraw


# 设置圆角
def circle_corder_image(im):
    rad = 10  # 设置半径
    circle = Image.new('L', (rad * 2, rad * 2), 0)
    draw = ImageDraw.Draw(circle)
    draw.ellipse((0, 0, rad * 2, rad * 2), fill=255)
    alpha = Image.new('L', im.size, 255)
    w, h = im.size
    alpha.paste(circle.crop((0, 0, rad, rad)), (0, 0))
    alpha.paste(circle.crop((0, rad, rad, rad * 2)), (0, h-rad))
    alpha.paste(circle.crop((rad, 0, rad * 2, rad)), (w-rad, 0))
    alpha.paste(circle.crop((rad, rad, rad * 2, rad * 2)), (w-rad, h-rad))
    im.putalpha(alpha)
    return im


# 生成二位码
def create_qrcode(url):
    qr = qrcode.QRCode(
        version=5,
        # 设置容错率为最高
        error_correction=qrcode.ERROR_CORRECT_H,
        box_size=10,
        border=1,
    )
    qr.add_data(url)
    qr.make(fit=True)

    img = qr.make_image()
    # 设置二维码为彩色
    img = img.convert("RGBA")
    icon = Image.open('file\\img\\80.png')
    w, h = img.size
    factor = 4
    size_w = int(w / factor)
    size_h = int(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
    icon = icon.resize((icon_w, icon_h), Image.ANTIALIAS)
    w = int((w - icon_w) / 2)
    h = int((h - icon_h) / 2)
    icon = icon.convert("RGBA")
    # 挖取中间的白图空间
    new_img = Image.new("RGBA", (icon_w + 4, icon_h + 4), (255, 255, 255))
    # 白图圆角处理
    new_img = circle_corder_image(new_img)
    # 粘贴白图
    img.paste(new_img, (w - 2, h - 2), new_img)
    # icon处理圆角
    icon = circle_corder_image(icon)
    # 粘贴icon
    img.paste(icon, (w, h), icon)
    img.show()
    # img.save('C:\\python\\thecover_project\\uploadqiniu\\file\\img\\wer.png', quality=1)


create_qrcode('http://www.baidu.com')

以上,都有注释。

另外说明一下,PIL在python3.x版本需要安装的是pillow。

 

猜你喜欢

转载自www.cnblogs.com/drewgg/p/12762053.html
今日推荐