Why reopen a file after checking it with verify?

verify checks for file problems without decoding all pixels. Reopen the image before subsequent pixel loading.

Pixel experiment and interpretation

Open a PNG twice to separate structural validation from pixel reading. Passing that check says nothing about whether the semantic label is correct.

from PIL import Image
from io import BytesIO

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

buf=BytesIO()
row([42]).save(buf,format='PNG')
raw=buf.getvalue()
with Image.open(BytesIO(raw)) as im:
    im.verify()
with Image.open(BytesIO(raw)) as im:
    value=im.getpixel((0,0))
value

Result 42

中文

图像校验后为什么要重新打开文件才能解码?

verify 尝试检查文件完整性而不解码所有像素,后续读取图像需要重新打开。

像素实验与适用边界

将一份 PNG 的完整性检查与像素读取分成两次打开。完整性通过仅说明该检查成功,不能证明内容标签正确。

from PIL import Image
from io import BytesIO

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

buf=BytesIO()
row([42]).save(buf,format='PNG')
raw=buf.getvalue()
with Image.open(BytesIO(raw)) as im:
    im.verify()
with Image.open(BytesIO(raw)) as im:
    value=im.getpixel((0,0))
value

结果 42

References / 参考来源

Keep reading / 继续阅读