【问题标题】:Is a PNG file size supposed to remain static when using Python PIL 'quality' parameter while saving?保存时使用 Python PIL“质量”参数时,PNG 文件大小是否应该保持静态?
【发布时间】:2021-03-16 20:09:59
【问题描述】:

据我所知,我的代码(如下)按预期运行。我打开一个图像,然后在保存时迭代地生成具有不同设置的图像副本,特别是在该步骤修改质量和优化值。我的目标是确定我的用例的最佳参数是什么,但在运行脚本时我发现了我不理解的结果。

无论我将“质量”设置为什么,生成的 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)

【问题讨论】:

    标签: python matplotlib python-imaging-library png


    【解决方案1】:

    documentation for the save method 提到了这一点:

    关键字选项可用于向作者提供附加说明。如果作者无法识别一个选项,它会被默默地忽略。每个作者的图像格式文档中描述了可用的选项。

    事实上,PNG writer 的文档没有提到 quality 选项,因此它是一个在保存调用中被忽略的值。

    【讨论】:

    • 对,png是无损的,所以不需要质量标志...如果您需要或多或少的分辨率,请更改dpi关键字参数
    猜你喜欢
    • 1970-01-01
    • 2011-01-15
    • 1970-01-01
    • 2020-02-17
    • 2013-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-12
    相关资源
    最近更新 更多