【问题标题】:Is there a way to measure the memory consumption of a PNG image?有没有办法测量 PNG 图像的内存消耗?
【发布时间】:2026-02-20 10:55:01
【问题描述】:

我想知道 Python 中是否有一种方法可以测量 PNG 图像的内存消耗。

对于我的测试,我必须使用图片 normal.pngevil.png。假设两个图像的大小都是 100kb。

normal.png 由每像素 1 个字节表示的数据组成。

evil.png\x00 字节和PLTE 组成。块 - 每个像素 3 个字节。

对于normal.png,我可以解压缩IDAT 数据块,测量大小并将其与原始文件大小进行比较,以获得大致的内存消耗。

但是如何处理evil.png

【问题讨论】:

  • 你的意思是,像width*height*depth

标签: python memory png


【解决方案1】:

您可以使用Pillow库来识别图像并获取像素数和the mode, which can be transformed into the bitdepth

from PIL import Image

mode_to_bpp = {'1':1, 'L':8, 'P':8, 'RGB':24, 'RGBA':32, 
               'CMYK':32, 'YCbCr':24, 'I':32, 'F':32}

i = Image.open('warty-final-ubuntu.png')
h, w = i.size

n_pixels = h * w
bpp = mode_to_bpp[data.mode]
n_bytes = n_pixels * bpp / 8

Image.open 还没有加载整个数据;有问题的压缩图像为 3367987 字节,4096000 像素,未压缩时使用 12288000 字节的内存;但是straceing python 脚本显示Image.open 仅从内存中的文件读取 4096 个字节。

【讨论】:

    最近更新 更多