尝试使用Python上的PIL和qrcode库将我的QR码背景更改为透明

问题描述 投票:0回答:1

我好像遇到了心理障碍。我有一个 python 脚本,它是一个基本应用程序,用于从 CSV 文件生成 QR 码并将其编译为 PDF。

我想做的是将二维码的背景更改为透明背景,而不是始终显示为黑色背景。我尝试使用 fpdf 库,将图像更改为 RGBA 等

请帮助我实现这一目标!

这是我生成二维码的代码部分:

def generate_qr_code_with_text(data, text_row1, text_row2, text_row3, output_path, qr_size_pixels=227):
    try:
        qr = qrcode.QRCode(
            version=1,
            error_correction=qrcode.constants.ERROR_CORRECT_L,
            box_size=10,
            border=4,
        )
        qr.add_data(data)
        qr.make(fit=True)

        img = qr.make_image(fill_color=(255,255,255), back_color=None)
        img = img.resize((qr_size_pixels, qr_size_pixels))

        final_img = Image.new('RGBA', (img.width, img.height + 90), color=(255, 255, 255, 0))
        final_img.paste(img, (0, 0))

        draw = ImageDraw.Draw(final_img)
        font = ImageFont.load_default()

        text_row1_position = (final_img.size[0] // 2, img.size[1] + 10)
        draw.text(text_row1_position, f"Row 1: {text_row1}", fill="black", font=font, anchor="mm")

        text_row2_position = (final_img.size[0] // 2, img.size[1] + 30)
        draw.text(text_row2_position, f"Row 2: {text_row2}", fill="black", font=font, anchor="mm")

        text_row3_position = (final_img.size[0] // 2, img.size[1] + 50)
        draw.text(text_row3_position, f"Row 3: {text_row3}", fill="black", font=font, anchor="mm")

        final_img.save(output_path)
        return True

    except Exception as e:
        print(e)
        return False
python python-imaging-library qr-code
1个回答
0
投票

改变一下

        img = qr.make_image(fill_color=(255, 255, 255), back_color="black")

        img = qr.make_image(fill_color=(255, 255, 255), back_color="transparent")
© www.soinside.com 2019 - 2024. All rights reserved.