Why can the same raw bytes describe differently shaped pictures?

frombytes interprets raw samples with the provided mode and size. The byte stream carries no shape of its own.

Pixel experiment and interpretation

Four values fit a strip or a square. Record scanline width in the sensor contract to avoid silently reshaping a valid buffer into the wrong image.

from PIL import Image

raw=bytes([1,2,3,4])
a=Image.frombytes('L',(2,2),raw)
b=Image.frombytes('L',(1,4),raw)
(a.getpixel((0,1)),b.getpixel((0,1)))

Result (3, 2)

中文

原始字节流有相同长度,为何能还原出不同形状?

frombytes 按调用者指定的模式与尺寸解释原始样本,字节流本身没有形状。

像素实验与适用边界

四个值既能排一列也能排成方块。传感器契约应注明每行宽度,以免一张有效图片显示为错位条带。

from PIL import Image

raw=bytes([1,2,3,4])
a=Image.frombytes('L',(2,2),raw)
b=Image.frombytes('L',(1,4),raw)
(a.getpixel((0,1)),b.getpixel((0,1)))

结果 (3, 2)

References / 参考来源

Keep reading / 继续阅读