How can pixel loading finish before the input stream closes?

load reads the current frame pixels into the image. A decoded single-frame image can outlive its original input stream.

Pixel experiment and interpretation

Decode before closing the memory stream, then sample the image. A multi-frame decoder may still require its source for later frames.

from PIL import Image
from io import BytesIO

def row(values):
    return Image.frombytes('L', (len(values), 1), bytes(values))

buf=BytesIO()
row([81]).save(buf,format='PNG')
buf.seek(0)
im=Image.open(buf)
im.load()
buf.close()
im.getpixel((0,0))

Result 81

中文

关闭图像输入流之前如何完成像素加载?

load 将当前帧的像素读入图像,单帧文件可在解码后脱离原输入流。

像素实验与适用边界

先解码再关闭内存流,之后仍能读取灰度。多帧格式还可能需要原文件来读取后续帧。

from PIL import Image
from io import BytesIO

def row(values):
    return Image.frombytes('L', (len(values), 1), bytes(values))

buf=BytesIO()
row([81]).save(buf,format='PNG')
buf.seek(0)
im=Image.open(buf)
im.load()
buf.close()
im.getpixel((0,0))

结果 81

References / 参考来源

Keep reading / 继续阅读