为什么使用PIL的“粘贴”功能后图片会掉色变块

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

编辑: 问题视频

我正在使用 tkinter、customtkinter、qrcode 和 Pillow (PIL) 库在 Python 中使用 GUI 开发 QR 码生成器。我使用(自定义)tkinter 作为 GUI,使用 qrcode 生成二维码,使用 PIL 为二维码添加标志。

Github 如果您想详细查看它。

例如,当尝试将此 AI 生成的汽车添加到我的二维码时,通常看起来像这样:Car unchanged

添加二维码后变成这样:qr code with car

如果你把车拉得很远,你会注意到构成汽车的小点实际上是小方块。

处理添加标志的代码如下:

import qrcode
import qrcode.image.svg
import tkinter
import customtkinter 
from PIL import Image

def select_logo(): # Gets called when someone presses the "select logo" button
    logo_path = tkinter.filedialog.askopenfilename(title="Select a logo",
        initialdir="/",
        filetypes=(
            ("Image file", "*.png"),
            ("Image file", "*.jpg"),
            ("Image file", "*.webp"),
            ("All files", "*.*")
            )
        )

    logo = Image.open(logo_path)
    logo = logo.resize((500,500))
    logo.save("temp/logo.png")
    update_ui() # Function to update the GUI. Doenst affect the qr code


def create_qr(mode=""):

    qr = qrcode.QRCode(
            version=round(version_slider.get()),    # Gets values of sliders and error correction
            box_size=round(boxsize_slider.get()),
            border=round(border_slider.get()),
            error_correction=get_error_correction()
    )
    qr.add_data(content_box.get("1.0","end-1c")) # Gets content from a textbox from row 1 idex 0 up to the end but deletes the last character (-1c) because using "end" always adds a linebreak at the end

   { a few lines 
         of unrelated code 
              here... (checking if "mode" is set to something else}

    elif logo_checkbox.get() == 1: # checks if logo addition is enabled
        img = qr.make_image(back_color=background_color_box.get(),fill_color=fill_color_box.get()) # Gets the selected color from the GUI and uses them for "back_color" and "fill_color"
        img = img.resize((2000,2000))
        logo = Image.open("temp/logo.png")
        img.paste(logo, (750,750))
        return img

    elif filetype_box.get() == ".svg": 
       return qr.make_image(image_factory=qrcode.image.svg.SvgImage) # Use svg imagefactory if selected
    else:
       return qr.make_image(back_color=background_color_box.get(),fill_color=fill_color_box.get())
   

def create_and_safe_qr():
    img = create_qr()
    img.save(f"QR-Codes/{filename_box.get()}{filetype_box.get()}") # Saves with chosen name and file extension

我不太确定徽标图像在过程中的哪一点被“损坏”,但我相信使用“粘贴()”方法时会发生这种情况,因为“临时”文件夹中的徽标已调整大小,由“select_logo”生成()" 函数,没有损坏。

我对编码还是很陌生,所以请原谅我可能犯的任何菜鸟错误。我还在学习。

谢谢大家的帮助:)

编辑: 出于某种原因,只有当代码的颜色设置为黑色且背景颜色设置为白色时才会发生这种情况。任何其他组合(即使是黑色背景上的白色二维码)都没有这个问题。

python image image-processing python-imaging-library qr-code
© www.soinside.com 2019 - 2024. All rights reserved.