簡體   English   中英

裁剪掉額外的透明像素后無法保存 PIL 圖像文件

[英]Can't save a PIL image file after cropping out extra transparent pixels

我有這個 function ,它采用 svg 徽標,將它們轉換為 png(第一個用於循環),刪除多余的冗余透明像素並將其保存到其目標文件夾(第二個用於循環)。

def convert_to_png(source_path, destination_path, output_w, output_h):
    if not os.path.exists(destination_path):
        os.mkdir(destination_path)

    # Turns SVG images to to PNG
    for i in os.listdir(source_path):
        new_file_name = i.split('.')
        new_file_name = new_file_name[0]
        cairosvg.svg2png(url=source_path + str(i), write_to=destination_path + str(new_file_name) + '.png',
                         output_width=output_w, output_height=output_h)

    for j in os.listdir(destination_path):

        img = cv2.imread(destination_path + j, cv2.IMREAD_UNCHANGED)
        img = cv2.cvtColor(img, cv2.COLOR_BGRA2RGBA)

        logo = Image.fromarray(np.uint8(img)).convert('RGBA').crop().getbbox()

        logo.save(destination_path + j, 'PNG')

這就是我調用 function 的方式:

convert_to_png(current_dir + '/riot_sponsors/', current_dir + '/new_logos/', 2000, 1500)

出於某種原因,我收到此錯誤:

logo.save(destination_path + j, 'PNG')
AttributeError: 'tuple' object has no attribute 'save'

我的目標是將新裁剪的 png 文件保存到destination_path

.getbbox()返回左、右、上、下坐標的元組。 這是返回給 logo 變量的內容。

如果要刪除圖像的透明部分,請使用以下代碼:

logo = Image.fromarray(np.uint8(img)).convert('RGBA')
logo = logo.crop(logo.getbbox())

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM