簡體   English   中英

保存時使用 Python PIL“質量”參數時,PNG 文件大小是否應該保持為 static?

[英]Is a PNG file size supposed to remain static when using Python PIL 'quality' parameter while saving?

據我所知,我的代碼(如下)按預期運行。 我打開一個圖像,然后在保存時迭代地生成具有不同設置的圖像副本,特別是在該步驟修改質量和優化值。 我的目標是確定什么是我的用例的最佳參數,但是在運行腳本時,我發現了我不理解的結果。

無論我將“質量”設置為什么,生成的 PNG 的大小都是相同的。 在“優化”( true/false ) 之間切換時,PNG 文件大小會發生變化,但在調整質量時不會發生變化。

這是預期的還是我在下面的代碼中出錯了?

'''I want to see how small I can go with the best picture quality'''

from PIL import Image
import matplotlib.pyplot as plt
from pathlib import Path
import os


def make_lists(result_images):
    '''Returns a dict of lists containing image size values'''
    plot_dict = {}
    for ext, val in result_images.items():
        for opt, var in val.items():
            plot_dict[f'{ext}-{opt}'] = var
    return plot_dict


def draw_result(plot_dict):
    '''Draws resulting image data as a graph'''
    colors = ['green', 'red', 'blue', 'orange']
    c = 0
    for key, val in plot_dict.items():
        plt.plot(val, color=colors[c], label=key)
        c += 1
    plt.legend()
    plt.show()


def generate_images():
    '''Generates N images with adjustments to optimization and quality with each output
    leaving the size the same each time'''
    im_path = 'full.jpg'
    out_path = 'out'

    if not os.path.exists(out_path):
        os.makedirs(out_path)

    im = Image.open(im_path)
    new_im = im.resize(im.size, Image.ANTIALIAS)

    qualities = [100, 75, 50, 25]
    optimize = [True, False]
    extens = ['png', 'jpg']

    result_images = {}

    for ext in extens:
        result_images[ext] = {}
        for opt in optimize:
            result_images[ext][opt] = []
            for q in qualities:
                fpath = f'{out_path}/{q}{opt}.{ext}'
                new_im.save(fpath, optimize=opt, quality=q)
                footprint = Path(fpath).stat().st_size
                result_images[ext][opt].append(footprint)
    return result_images


result_images = generate_images()

plot_dict = make_lists(result_images)

draw_result(plot_dict)

save 方法的文檔提到了這一點:

關鍵字選項可用於向作者提供附加說明。 如果作者不識別選項,它會被默默地忽略。 每個 writer 的圖像格式文檔中描述了可用的選項。

實際上, PNG編寫器的文檔沒有提到quality選項,因此它是在保存調用中被忽略的值。

暫無
暫無

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

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