How can a decoder assemble an image received in chunks?

ImageFile.Parser accepts encoded chunks through feed and finalizes the image when close signals end of input.

Pixel experiment and interpretation

Split a PNG inside its signature and feed the pieces in order. Network chunk boundaries need not align with the format, but missing bytes can still break decoding.

from PIL import Image, ImageFile
from io import BytesIO

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

buf=BytesIO()
row([33]).save(buf,format='PNG')
raw=buf.getvalue()
p=ImageFile.Parser()
p.feed(raw[:3])
p.feed(raw[3:])
p.close().getpixel((0,0))

Result 33

中文

接收分块图像数据时怎样在末尾取得完整图像?

ImageFile.Parser 的 feed 逐块接收编码数据,close 在输入结束时完成解析。

像素实验与适用边界

把一份 PNG 在签名中间切开,按原顺序交给解析器。网络分块边界无需与图像结构对齐,但丢失字节仍可能导致解码失败。

from PIL import Image, ImageFile
from io import BytesIO

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

buf=BytesIO()
row([33]).save(buf,format='PNG')
raw=buf.getvalue()
p=ImageFile.Parser()
p.feed(raw[:3])
p.feed(raw[3:])
p.close().getpixel((0,0))

结果 33

References / 参考来源

Keep reading / 继续阅读