Why can't raw tobytes output be treated as a PNG file?

Default tobytes emits raw pixel samples in mode order, without a header or encoded file container.

Pixel experiment and interpretation

One RGB pixel takes three bytes in this example. A receiver also needs dimensions, channel order and layout to reconstruct the image.

from PIL import Image

Image.new('RGB',(1,1),(1,2,3)).tobytes().hex()

Result '010203'

中文

为什么不能把 tobytes 的结果直接当 PNG 文件?

默认 tobytes 返回按照图像模式排列的原始像素,缺少文件头和编码容器。

像素实验与适用边界

一个红绿蓝像素正好对应三个字节。接收端还要知道宽高、通道顺序和布局才能还原图像。

from PIL import Image

Image.new('RGB',(1,1),(1,2,3)).tobytes().hex()

结果 '010203'

References / 参考来源

Keep reading / 继续阅读